2017-04-07 42 views
0

我想創建一個服務,它將負責打開引導彈出式錯誤和成功溝通。我有兩個組件ErrorComponent,SuccessComponent和一個名爲CommunicatesComponent的服務。我想使用這項服務來打開酥料餅像Angular 2服務打開錯誤popover

service.error('some error') 
service.success('success!') 

,這應該與提供的文本作爲參數顯示酥料餅。我做的是服務設置組件屬性一樣其次,在這種服務中使用該屬性:

ErrorComponent

export class ErrorComponent implements OnInit { 
    public text:string; 
    @ViewChild('errorPopover') private errorPopover: NgbPopover; 

    constructor(private communicatesService:CommunicatesService) {  
    } 

    public ngOnInit() { 
     this.communicatesService.setErrorComponent(this) 
    } 
} 

服務:

@Injectable() 
export class CommunicatesService { 
    private errorComponent:ErrorComponent 

    public setErrorComponent(component:ErrorComponent) { 
     this.errorComponent = component; 
    } 

    public error(text:string) { 
     console.log(this.errorComponent) 
     // this.errorComponent.text = text; 
    } 
} 

Unfortunitelly,似乎我的組件對象提供的不好,因爲控制檯日誌打印未定義。應該怎麼做?

問候

回答

1

有兩件事情我會在你的設計更改

  1. ErrorComponent和CommunicatesService依賴於對方。最好避免它 - CommunicatesService可以輕鬆地使用不同的組件。所以你可以創建一個rx Observable公共屬性的服務,所以任何組件都可以訂閱它。當service.success('success!')時,該服務將發送消息文本給訂閱者。
  2. 在ErrorComponent中,您將popover組件作爲@ViewChild獲取。你可以考慮將ErrorComponent.text直接綁定到彈出窗口(反轉依賴關係)。

這些更改可以解決您的問題,並使設計更加寬鬆 - 更易於理解和維護。

+0

如何實施解決方案1? –

+0

要創建Observable對象,請使用Rx.Subject:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/subject.md它允許您輕鬆地將消息推送到它。你只需調用'subject.onNext(message);'並且訂戶得到通知。 –

+0

我已經安裝了rxjs並且已導入,但是在代碼中收到'無法找到名稱Rx':private errorObservable = new Rx.Subject(); –