Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Superclass Fields from Angular 5 Component

I have a superclass which contains common functionality for components.

export class AbstractComponent implements OnInit {

  public user: User;

  constructor(public http: HttpClient) {
  }

  ngOnInit(): void {
    this.http.get<User>('url').subscribe(user => {
      this.user = user;
    });
  }
}

I have a subclass which implements this superclass.

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent extends AbstractComponent {

  constructor(public http: HttpClient) {
    super(http);
  }
}

In the headers template I am trying to access the user

<mat-toolbar color="primary">
  <span *ngIf="user">Welcome {{user.username}}!</span>
</mat-toolbar>

But the user field is not being resolved. How can I access a superclass's fields from a subclass?

like image 339
cscan Avatar asked Nov 25 '17 19:11

cscan


2 Answers

You are getting an error because the user object is not available at load.

Either initalise it or use the safe navigation operator (?.) inside your template

initalise:

public user: User = new User();

safe navigation:

<span>Welcome {{user?.username}}!</span>
like image 60
Poul Kruijt Avatar answered Oct 24 '22 08:10

Poul Kruijt


This approach works but it is not a good practice. In such cases it would be better to use async pipe:

export class AbstractComponent {
  user$;
  constructor() {
    // your real http request should be here
    this.user$ = Observable.of({name: 'John Doe'});
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>Hello {{(user$ | async).name}}</div>
  `,
})
export class App extends AbstractComponent {
  constructor() {
    super();
  }
}
like image 2
shohrukh Avatar answered Oct 24 '22 08:10

shohrukh