2016-11-04 58 views
0

我正在使用Provider注入器將Signin組件中的命令發送到Profile組件以註銷。儘管控制檯日誌顯示Signout函數已按預期工作,但(HTML)* ngIf指令不會相應更改。兩個不同的組件如何相互通信?

我在做什麼錯?

**Signin component** 

import {Component, OnInit, Injectable } from '@angular/core'; 

import {ProfileUserComponent} from '../profile.user.component/profile.user.component' 


@Component({ 
    selector: 'signin-button', 
    template: `<button (click)="onSignOut()" *ngIf="loggedIn === true " >Sign Out</button> 
<button (click)="onSignIn()" *ngIf="loggedIn !== true " >Sign In</button> 
`, 
    providers: [ProfileUserComponent] 


}) 




@Injectable() 
export class SigninComponent { 

loggedIn: boolean; 

constructor(public http: Http, private profileUserComponent: ProfileUserComponent){} 

     ngOnInit(): any{} 

onSignOut(): void{ 

// send command to the profile component 
this.profileUserComponent.signout(false);  

} 

} 





**ProfileUserComponent** 
import {Component, OnInit, Injectable} from '@angular/core'; 



    @Component({ 
      selector:'profile-user', 
      template: `<img class="ui mini image" src="image1.jpg" *ngIf="loggedIn === true"> 

    <img class="ui mini image" src="image2.jpg" *ngIf="loggedIn === false"> 

    `, 

    }) 

     signout(status){ 
     this.loggedIn = status; 
     console.log ("logged out", this.loggedIn); // Console log tells me that "Logged Out False" 
}  


} 

回答

0

您的整個代碼需要重寫。您試圖將一個組件注入另一個組件,這是錯誤的。您將服務注入組件。

如果ProfileUserComponent和SigninComponent都必須是具有UI的組件,那麼您可以創建一個知道登錄狀態並注入這兩個組件的公共服務。一個組件可以設置服務屬性(例如isSignedIn:EventEmitter)的登錄狀態,該狀態將發送關於登錄狀態的事件,另一個組件將監聽此事件。

在旁註:@注射註釋不與組件一起使用。

+0

嗨Yakov,如果我正確地理解了你,構建* ProfileUserComponent的正確方法是讓該組件監聽更改?這是不同的,因爲現在在Angular2中我們使用Rxjs庫? –

+0

如果同時顯示兩個兄弟組件,則引入一個服務並讓第一個組件修改服務,該服務將在每次此類修改時觸發一個事件。如果將此服務注入第二個組件,則它可以訂閱這些事件:myCommonService.varOfTypeEventEmitter.subscribe()。 另一種情況是通過使用路由器。如果第二個組件顯示在路由器插座中,它可以通過訂閱ActivatedRoute的params屬性(它必須注入到第二個組件中)來訂閱來自第一個組件的更新。 –

相關問題