繁体   English   中英

Angular 6:将id从一个组件传递到另一个组件

[英]Angular 6: pass id from one component to another component

我的情况:

我有一个登录组件,当我将登录时,我将从API获得响应

{
  code: 200,
  id: 4,
  msg: "success",
  user: "Sourav"
}

我想将此id发送到Candidate组件,cv Details Component和Key技能组件。

我的代码

MyCommonService:

import{ Injectable } from'@angular/core';
@Injectable({
providedIn: 'root',
})
export class CommonUserService {
  public userId;

  constructor() {}

  setUserLoggedIn(Id) {
    this.userId = Id;
    console.log(this.userId);
  }

  getUserLoggedIn() {
    console.log(this.userId);
    return this.userId;
  }

}

LoginComponent

这里我使用普通服务设置id

login() {
  if (this.seekerlogin.code == '200') {
    this.commonuserservice.setUserLoggedIn(this.seekerlogin.id);
  }
}

Candiadate组件

这里显示id是Undefined

 submit(){
 let id = this.commonuserservice.getUserLoggedIn(); // Here showing id is  
 Undefined
 let name = this.name;
 this.companydetailssevice.candidateServiceMethod(id,name)
  .subscribe(
    data => {
        this.ResponseVariable= data;
           if(this.ResponseVariable.code =='200'){ 
            this.router.navigate(['key_skill']);                   
             }
    },
    error => alert(error),
    () => console.log(this.ResponseVariable)
  );
}

请帮助我,我做错了或告诉我任何其他解决方案

我们有多种方法可以将数据从一个控制器共享到另一个控 但是以简单的方式你可以使用localStorage。

请检查示例代码。

第1步:改变您的服务

import { Injectable } from '@angular/core';

@Injectable()
export class CommonUserService {
    constructor() { }
    //State Management
    setSession(key: string, value: any): void {
        //sessionStorage.setItem(key, JSON.stringify(value));
        localStorage.setItem(key, JSON.stringify(value));
    }
    getSession(key: string): any {
        if (typeof window !== 'undefined') {
            //let retrievedObject = sessionStorage.getItem(key) as string;
            let retrievedObject = localStorage.getItem(key) as string;
            return retrievedObject;
        }
    }
    clearSession(): void {
        localStorage.clear();
    }
}

第2步:设置和获取会话值。

 this._commonUserService.setSession('UserId', UserId);
 let userId= this._commonUserService.getSession('UserId');

它应该工作。 你正在做的是正确的方法。 只需确保在所有组件中运行CommonUserService的单个实例。 确保已将CommonUserService添加到模块中的providers数组中,而不是添加到单个组件中。

 import{ Injectable } from'@angular/core'; @Injectable() export class CommonUserService { public userId; constructor() {} setUserLoggedIn(Id) { this.userId = Id; console.log(this.userId); } getUserLoggedIn() { console.log(this.userId); return this.userId; } } 

然后在你的模块中

 @NgModule({ declarations: [ AppComponent, ItemDirective ], imports: [ ], providers: [CommonUserService], bootstrap: [AppComponent] }) export class AppModule { } 

还有你的组成部分

 @Component({ selector: 'app-bank-account', template: ` Bank Name: {{ bankName }} Account Id: {{ id }} ` }) export class BankAccountComponent { bankName: string|null = null; id: string|null = null; constructor(private commonService: CommonUserService){ } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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