[英]How I assign a value to variable from constructor in angular?
Problem with my Angular app.我的 Angular 应用程序出现问题。 This is my first angular web.
这是我的第一个 angular web。 I want to assign a value to my variable named
_name
from the constructor.我想从构造函数中为名为
_name
的变量赋值。 I tried the below way but didn't work.我尝试了以下方法,但没有奏效。 How can I assign a value for that?
我怎样才能为此分配一个值? The value comes to that page in the
console.log
the value is displayed.该值出现在
console.log
中的该页面,该值被显示。 I want to assign that value to my _name
variable and display the value in the HTML page when the page load.我想将该值分配给我的
_name
变量,并在页面加载时在 HTML 页面中显示该值。 How can I do that?我怎样才能做到这一点?
This is my current code这是我当前的代码
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;
});
}
I would rewrite your code like below avoiding complication我会像下面这样重写您的代码,以避免复杂化
import { Subject } from 'rxjs';
import { takeUntil, tap } from 'rxjs/operators';
export class DashboardTemplateComponent implements OnInit {
destroyed$ = new Subject();
inAuthenticate = false;
_name: any;
name$ = this.authService.user.pipe(
tap(user => this._name = user.name),
tap(user => this.inAuthenticate = !user ? false : true)
takeUntil(this.destroyed$)
)
constructor(private router: Router, private authService: userService ) {
}
ngOnInit(): void {
this.name$.subscribe();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.