2017-09-19 125 views
0

我有一個名爲LoginResponse的變量,它存儲我登錄後從服務器獲得的響應。我成功登錄後將應用重定向到儀表板。 我希望在我的Dashboard.component.ts訪問LoginResponse無法訪問子組件中的父組件變量 - 角4

登錄功能在APP COMP-

onLogin(form: NgForm) { 
    console.log(form); 
    this.serverService.Login(JSON.stringify(form.value)) 
     .subscribe(
     (response) => { 
     form.reset(); 
     this.LoginResponse = response.json().data; 
     jQuery(this.modalcloser.nativeElement).modal('hide'); 
     this.router.navigate(['/dashboard']); 
     console.log(this.LoginResponse); 
     }, 
     (error) => {console.log(error.json()), 
    jQuery(this.modalcloser.nativeElement).modal('hide'); 
    jQuery(this.errormodal.nativeElement).modal('show'); 
     this.errormsg = (error.json().error); 
    } 
    ); 
    } 

儀表板COMP-

import { Component, OnInit, Input } from '@angular/core'; 
import { Router } from '@angular/router'; 

@Component({ 
    selector: 'app-dashboard', 
    templateUrl: './dashboard.component.html', 
    styleUrls: ['./dashboard.component.css'] 
}) 
export class DashboardComponent implements OnInit { 

    constructor(private router: Router) { } 

    @Input() LoginResponse: {token: string, teamname: string, member1name: string, member2name: string, member3name: string }; 

    ngOnInit() { 
    console.log(this.LoginResponse); 
    } 

    // logOut() { 
    // this.router.navigate(['/']); 
    // } 

} 

APP目錄 - enter image description here

+0

如何做在父HTML儀表板組件? – Sajeetharan

+0

在OP中添加了屏幕截圖。 @Sajeetharan –

+0

不是目錄,你如何在html中傳遞值。粘貼父組件的代碼 – Sajeetharan

回答

1

隨着以上實現的事件發射器,你的父組件應該有

<app-dashboard [LoginResponse]="LoginResponse"></app-dashboard> 

第二個辦法: 可以使用,保持狀態和所有子組件訂閱狀態和家長服務共享跨組件變量。

@Injectable() 
export class sharedService { 
LoginResponse:any; 
constructor() { 
} 
Initialize() { 
    this.LoginResponse = assign value here; 
} 

get() { 
    return this.LoginResponse; 
} 
} 

然後在DASHBOARD.ts

import { sharedService } from '/services/sharedService.service'; 
constructor(private sharedSer : sharedService) { 

    } 

Update(){ 
    this.LoginResponse = this.sharedSer.get(); 
} 
+0

你能證明我該怎麼做?這將是一個很大的幫助! –

+0

上面的一個應該有所幫助 – Sajeetharan

0

在你app.component.html,注入儀表板組件象下面這樣:

<app-dashboard [LoginResponse]="LoginResponse"></app-dashboard>