嗨,大家好,我登录后在我的有角项目中,我的后端API将生成JWT令牌并传递到前端。因此,在那之后,我将解码JWT令牌并从该令牌中获取一些详细信息。因此,该过程在login.component.ts中完成。因此,我想将解码数据传递给我的顶部栏组件。问题是top.bar组件已被加载到应用程序中。你能帮助我吗。
角度7 cli
onSubmit(form:NgForm){
//some code here for login authentication----------------
const helper = new JwtHelperService();
const decoded= helper.decodeToken(result.token);
console.log(decoded);
}
ngOnInit() { }
答案 0 :(得分:4)
可以通过以下方式完成:
使用loginSubject
创建共享服务:
@Injectable()
export class StateService {
loginSubject: Subject<any> = new Subject();
...
}
在Login.component.ts
中发送消息:
constructor(
private stateService: StateService
) {}
onSubmit(form: NgForm) {
// some code here for login authentication----------------
const helper = new JwtHelperService();
const decoded= helper.decodeToken(result.token);
this.stateService.loginSubject.next(decoded);
console.log(decoded);
}
订阅loginSubject
中的Top-Bar.component.ts
:
constructor(
private stateService: StateService
) {}
ngOnInit() {
this.stateService.loginSubject.subscribe(data => {
// decoded
});
...
}
答案 1 :(得分:0)
Few of the many ways in Angular Component's Interaction,
1) If Top-Bar.component.html has to be displayed as part of login html then,
You can pass in the value to Top-Bar.component.ts using @Input variable
Please read through https://angular.io/guide/component-interaction
2) If Top-Bar.component is all together independent of login module, you can have service
created and assign the variable to the service and use it for component interaction.
Please read through https://angular.io/tutorial/toh-pt4