繁体   English   中英

如何通过服务将数据从Angular2中的一个组件发送到另一个组件

[英]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)都已加载,一旦您从登录组件中设置了服务中的数据,您将重定向到仪表板组件,但此组件当时已加载加载应用程序的时间,以便更改不会在此触发,直到您刷新应用程序。

备用

  1. 为什么不使用@input@output 如果可能的话,请使用输入和输出,因为这是在组件之间传递数据的标准方法。

  2. 如果要使用相同的方法,则必须使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM