2016-11-10 157 views
5

我正在加載標籤之間的一些div。它的波紋管。Angular2:如何從父組件傳遞給孩子?

這裏是我的index.html

<html> 
<script> 
System.import('app').catch(function(err){ console.error(err); }); 
</script> 
</head> 

<!-- 3. Display the application --> 

<body> 
<my-app>Loading...</my-app> 
</body> 
</html> 

app.module.ts

@NgModule({ 
imports: [ 
    BrowserModule, 
    FormsModule, 
    AppRoutingModule 
], 
declarations: [ 
    AppComponent, 
    LoginComponent, 
    HomeComponent, 
    NewsfeedComponent, 
    TopBarComponent, 
    SideMenuComponent 
], 
providers : [ 
    AuthGaurd 
], 
bootstrap: [ 
    AppComponent 
] }) 
export class AppComponent {} 

home.component.ts

@Component({ 
    selector: 'home', 
    moduleId: module.id, 
    templateUrl: 'home.component.html', 
    providers : [ 
     LoginService 
    ] 
}) 

export class HomeComponent implements OnInit{ 
isLoggedin : boolean; 
constructor (private loginService : LoginService) { } 
ngOnInit(): void { 
    this.loginService.getLogged().subscribe((isLoggedIn: boolean) => { 
     this.isLoggedin = isLoggedIn; 
    }); } 
} 

home.component.html 

<side-menu *ngIf='isLoggedin'></side-menu> 
<top-bar *ngIf='isLoggedin'></top-bar> 
<router-outlet></router-outlet> 

auth.gaurd.ts

@Injectable() 
export class AuthGaurd implements CanActivate{ 
    constructor(private router : Router) { 
    } 
    canActivate(){ 
     if (localStorage.getItem('isLogin')){ 
      return true; 
     } 
     this.router.navigate(['/login']) 
     return false; 
    } 
} 

login.service.ts

@Injectable() 
export class LoginService { 
    private subject: Subject<boolean> = new Subject<boolean>(); 
    constructor(private router : Router) { 
    } 
    login(){ 
     this.setLogged(true); 
     localStorage.setItem("isLogin","true"); 
     this.router.navigate(['/news-feed']); 
    } 
    logout(){ 
     this.setLogged(false); 
     localStorage.removeItem("isLogin"); 
     this.router.navigate(['/login']); 
    } 
    getLogged(): Observable<boolean> { 
     return this.subject.asObservable(); 
    } 
    setLogged(val : boolean): void { 
     this.subject.next(val); 
    } 
} 

login.component.ts

@Component({ 
    selector: 'login', 
    moduleId: module.id, 
    templateUrl: 'login.component.html' 
}) 

export class LoginComponent { 
    constructor (private loginService : LoginService) { 
    } 

    login(){ 
     this.loginService.login() 
    } 
} 

login.component.html

<input type="number」 #mobileNumber /> 
<input type="password" #password /> 
<input type="button" (click)="login()"> 

newsfeed.component.ts

@Component({ 
    selector: 'newsfeed', 
    moduleId: module.id, 
    templateUrl: 'newsfeed.component.html', 
}) 

export class NewsfeedComponent { 

} 

newsfeed.component.html

一些HTML文本.... !!!!

APP-routing.module.ts

@NgModule({ 
imports: [ 
    RouterModule.forRoot([ 
     { 
      path : 'login', 
      component : LoginComponent 
     }, 
     { 
      path : 'news-feed', 
      component : NewsfeedComponent, 
      canActivate : [AuthGaurd] 
     }, 
     { 
      path : '', 
      redirectTo : '/news-feed', 
      pathMatch : 'full' 
     } 
     { 
      path: '**', 
      component: LoginComponent 
     } 
    ]) 
], 
exports: [ 
    RouterModule 
] 
}) 
export class AppRoutingModule {} 

其實它的正常工作,當我與點擊去。像它的發射完美比點擊登錄按鈕它轉發給新聞源並顯示預期的結果。但是當我從瀏覽器url,它沒有加載側欄和頂部的酒吧組件從我遇到這個問題的home.html

+0

您需要使用共享服務與路由器https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service添加組件通信 –

+0

我試過這個。它在點擊時工作正常,但在瀏覽器網址時無法正常工作。 –

+0

您需要提供更多信息。我不知道你想要完成什麼,或者你嘗試了什麼,或者問題可能出在哪裏。 –

回答

1

我不知道這一切固定,但我認爲你想讀的localStorage值率先拿到了最近存儲的狀態,如果你使用BehaviorSubject聽衆還獲得了最後的狀態,如果this.subject.emit()被稱爲用戶是以前訂閱。

@Injectable() 
export class LoginService { 
    //private subject: Subject<boolean> = new Subject<boolean>(false); 
    private subject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(); // <<< changed 
    constructor(private router : Router) { 
     this.sublect.next(logalStorage.getItem('isLogin')); // <<< added 
    } 
    login(){ 
     this.setLogged(true); 
     localStorage.setItem("isLogin","true"); 
     this.router.navigate(['/news-feed']); 
    } 
    logout(){ 
     this.setLogged(false); 
     localStorage.removeItem("isLogin"); 
     this.router.navigate(['/login']); 
    } 
    getLogged(): Observable<boolean> { 
     return this.subject.asObservable(); 
    } 
    setLogged(val : boolean): void { 
     this.subject.next(val); 
    } 
} 
+0

它給予運行時錯誤,因爲以下行 private subject:BehaviorSubject = new BehaviorSubject (); // <<<已更改 提供的參數不匹配調用目標的任何簽名。 –

+0

然後,它應該可能是'new BehaviorSubject (false);' –

+0

上面的一個刪除了運行時錯誤,但沒有給出預期的輸出。 –

3

。這是我如何解決這種情況;

  • 創建觀察的領域共享服務作爲官方的角度文檔
  • 在您的導航欄組件解釋說,從共享服務訂閱值,顯示導航欄
  • 在登錄和註銷頁面,更新的價值。由於您已經訂閱了該值,訂閱者自己處理此情況
  • 創建身份驗證服務。添加一個類似於這個的方法來詢問你的後端,是請求驗證的;
//method parameters depend on what you want 
isAuthorized(url: string, errorCallback: (any) => void) { 
     let body = JSON.stringify(url) 
     return this.http.post('account/isauthorized', body) 
      .map((response: Response) => { 
       //update value to display navigation bar if user is authenticated 
       yourSharedService.observableField.next(true); 
       return true; 
      }) 
      .catch((response: Response) => { 
       errorCallback(response.status); 
       return Observable.of(false); 
      }); 
    } 
  • 創建認證後衛和調用isAuthorized方法canActivatecanLoadCanActivateChild

  • 在你的回調中,處理未經授權的請求。你可以將用戶重定向到錯誤頁面或刪除導航欄,以及任何你想要的。

我希望它有幫助!

+0

不加載側欄和頂部欄組件。不工作 –

+0

如果你根據我的回答創建了一個已經嘗試過的工具,我可以做出改變並提供更好的幫助。 – ulubeyn

相關問題