我有兩個組件在同一個標籤。我想將數據從一個組件傳遞到另一個組件。我可以將數據設置爲service.But從服務我不想爲我工作。我想從login.component.ts設置數據並從managerdashboard.component.ts獲取數據。我可以如何解決該問題。我可以將數據設置爲服務,但我沒有從服務獲取數據。請幫幫我。如何通過服務將數據從一個組件發送到Angular2中的另一個組件
sso.service.ts
import { Injectable } from '@angular/core';
export interface User {
userId:number;
aemUserId:string;
role: string;
authorization: string;
userName: string;
}
@Injectable()
export class SsoService {
public user:User;
public checkedDatas:Array<any> = [];
setUser(user) {
debugger;
this.user = user;
console.log('setUser : ',this.user);
}
getUser() {
console.log('getUser : ',this.user);
return this.user;
}
isLoggedIn() {
return this.user && this.user.userName;
}
}
app.router.ts
import {ModuleWithProviders} from '@angular/core';
import {Routes,RouterModule, CanActivate} from '@angular/router';
import {AppComponent} from './app.component';
import { LoginComponent } from './login/login.component';
import { ManagerdashboardComponent } from './managerdashboard/managerdashboard.component';
export const router:Routes = [
{ path:'', redirectTo:'login', pathMatch:'full' },
{ path: 'login', component: LoginComponent },
{
path: 'aem',
component: AemHomeComponent,
children: [
{ path:'manager',component:ManagerdashboardComponent },
] },
// { path: '**', component: NotFoundComponent}
];
export const routes:ModuleWithProviders = RouterModule.forRoot(router);
login.component.ts
getSSO(ssoid){
console.log('getSSO new : ',ssoid);
this.authGuard.getAuth(ssoid)
.subscribe(resp => {
console.log("getSSO response",resp);
here I am setting data to service
this.authService.setUser(resp);
console.log("14-08-2017",this.authService.getUser())
this.router.navigate(
['aem', resp.role.toLowerCase()],
{ queryParams: { role:resp.role,sso_id:ssoid,auditorName:resp.userName}}
);
})
}
managerdashboard.component.ts
ngAfterViewInit(){
//Here I am getting data from service.
console.log("THIS IS MOHIT TRIPATHI",this.ssoservice.getUser());
}
你有任何控制檯錯誤?爲此文件添加您的構造函數代碼:'managerdashboard.component.ts' – Faisal