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?
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>
                        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();
  }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With