Angular 4 - @ViewChild 未定义对父元素视图的访问

Angular 4 - Access to father element view is undefined with @ViewChild

我需要创建一个模式来管理错误。所以我想最好的解决办法是把这个模式放在我的 app.component 中,这样我就可以在我的项目中使用一个模式:

<my-dialog #MyErrorDialog>
    ...
</my-dialog>

现在我需要在出现 http 代码时在许多组件或服务中打开此模式,但参考 ID:

@ViewChild('MyErrorDialog') MyErrorDialogReference: MyDialog; 

MyErrorDialogReference 在我的 child component/service 中是 undefined因为模式在应用程序组件中。

我不想使用 @Input/@Output

您可以将 service 用作:

错误服务

public errorMessage = new Subject<string>();
setErrorMessage(value: string) {
    this.errorMessage.next(value);
}

任何其他组件 通知服务有关错误

constructor(public errorService: ErrorService) { }
setMessage(message) { // call this method whenever you get error
    this.errorService.setErrorMessage(message);
}

app.component 应用组件接收错误

errorMessage: string;
errorSubscription: Subscription;
constructor(public errorService: ErrorService) { }
ngOnInit() {
    this.errorSubscription = this.errorService.errorMessage.subscribe(
        (message) => {
            this.errorMessage = message;
            // open dialog with message
        }
    );
}
ngOnDestroy() {
    this.errorSubscription.unsubscribe();
}