【问题标题】:How I assign a value to variable from constructor in angular?如何从角度的构造函数中为变量赋值?
【发布时间】:2021-04-03 20:37:41
【问题描述】:

我的 Angular 应用程序有问题。这是我的第一个角网。我想从构造函数中为名为@9​​87654322@ 的变量赋值。我尝试了以下方法,但没有奏效。我怎样才能为此分配一个值? 该值在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


【解决方案1】:

我会像下面这样重写你的代码以避免复杂化

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();
      }
  }

【讨论】:

  • 1) 你打算订阅name$,2) 如果你开始实现它,你应该完全添加OnDestroy 逻辑。 (而且你不需要多次点击,只需添加{})。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多