[英]In angular2 need to send data from one component to another component
[英]How to send data from one component to another component in Angular2 through service
我在同一標簽上有兩個組件。我想將數據從一個組件傳遞到另一組件。我可以將數據設置為服務。但是從服務獲取對我不起作用。我想從login.component.ts設置數據並從managerdashboard.component.ts獲取數據。如何解決此問題。我可以將數據設置為服務,但無法從服務獲取數據。請幫助我。
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)都已加載,一旦您從登錄組件中設置了服務中的數據,您將重定向到儀表板組件,但此組件當時已加載加載應用程序的時間,以便更改不會在此觸發,直到您刷新應用程序。
備用
為什么不使用@input
和@output
? 如果可能的話,請使用輸入和輸出,因為這是在組件之間傳遞數據的標准方法。
如果要使用相同的方法,則必須使用observable and subscribe
以偵聽更改,而無需刷新頁面。 你可以在這里讀出這個答案
您好您在服務中的get語句沒有返回類型。
getUser(): User {
console.log('getUser : ',this.user);
return this.user;
}
您正在使用this.authService.setUser(resp);
設置數據this.authService.setUser(resp);
但是使用this.ssoservice.getUser()
獲取數據將檢查這是否是錯誤的。
您正在ngAfterViewInit
中獲取數據,您應該正在獲取數據。 通過在目標組件中聲明@input()
變量來嘗試ngOnchange。 @input()
可用於在任何組件中利用ngOnChanges生命周期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.