【发布时间】:2021-04-03 20:37:41
【问题描述】:
我的 Angular 应用程序有问题。这是我的第一个角网。我想从构造函数中为名为@987654322@ 的变量赋值。我尝试了以下方法,但没有奏效。我怎样才能为此分配一个值?
该值在console.log 的那个页面中显示出来。我想将该值分配给我的 _name 变量,并在页面加载时在 HTML 页面中显示该值。我该怎么做?
这是我当前的代码
export class DashboardTemplateComponent implements OnInit, OnDestroy {
private userSub: Subscription;
inAuthenticate = false;
_name: any;
constructor(private router: Router, private authService: userService ) {
this.userSub = this.authService.user.subscribe(user => {
console.log(user.token);
return this._name = user.name;
});
}
ngOnInit(): void {
this.userSub = this.authService.user.subscribe(user => {
this.inAuthenticate = !user ? false : true;
return this._name = user.name;
});
}
【问题讨论】:
-
删除
return关键字 -
我已删除但仍无法正常工作
-
你得到了什么?并且不需要两次调用服务(构造函数和初始化)
-
是的,我修改我的代码如下。但是我在 html 页面中得到一个空值。在控制台中显示了该值。导出类 DashboardTemplateComponent 实现 OnInit, OnDestroy { private userSub: Subscription; inAuthenticate = false; _name:任何;构造函数(私有路由器:路由器,私有 authService:userService){}); } ngOnInit(): void { this.userSub = this.authService.user.subscribe(user => { this.inAuthenticate = !user ? false : true; this._name = user.name; }); }}
-
你在订阅区
console.log(user)得到了什么
标签: angular typescript data-binding