我有一个Login组件,当我登录时,我将收到来自API之类的响应
{
code: 200,
id: 4,
msg: "success",
user: "Sourav"
}
我想将此ID发送给候选组件,cv详细信息组件和关键技能组件。
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;
}
}
我在这里使用通用服务设置ID
login() {
if (this.seekerlogin.code == '200') {
this.commonuserservice.setUserLoggedIn(this.seekerlogin.id);
}
}
此处显示的ID未定义
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)
);
}
请帮助我哪里做错了,或者告诉我其他解决方案
答案 0 :(得分:2)
我们有多种方法可以将数据从一个控制器共享到另一个控制器。 但是以简单的方式,您可以使用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');
答案 1 :(得分:1)
应该可以。您正在做的事是正确的方法。只要确保您在所有组件中都运行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){
}
}