2017-11-25 205 views
3

我有一個超類,它包含組件的常用功能。從角度5組件訪問超類字段

export class AbstractComponent implements OnInit { 

    public user: User; 

    constructor(public http: HttpClient) { 
    } 

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

我有一個實現這個超類的子類。

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

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

在頭模板我試圖訪問用戶

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

但用戶字段沒有被解決。我如何從一個子類訪問超類的字段?

+0

您確定用戶獲取正確嗎?我使用完全相同的繼承,它對我來說工作得很好。 –

+0

試着把它放在你的子類HeaderComponent中,看它是否先工作。 – realharry

回答

4

您收到錯誤消息,因爲user對象在加載時不可用。

無論initalise或使用安全的導航操作(?.)您的模板內

initalise:

public user: User = new User(); 

航行安全:

<span *ngIf="user">Welcome {{user?.username}}!</span> 
1

這種方法有效,但這不是一個好習慣。在這種情況下,使用async管道會更好:

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(); 
    } 
} 
+0

是的你是對的,我同意這個答案在這種情況下使用異步管道是更正確的方法。 qurboni40。 + – komron