提问者:小点点

如何从角度项目中引用组件上局部变量上服务中的变量?


我有一个UserService,当我的用户在我的应用程序上签名时,我用来自用户的数据填充它,以显示在我的所有组件中。

但是当我像这样引用对象时,我面临一个小问题:

 ngOnInit() {
    this.userModel = this.userService.getUserModel();
 }

他在第一次加载时工作得很好,但是我有一个更改用户数据的页面,我想要在我所有的应用程序中反映出来,所以当我更改这个对象this.usermodel时,所做的更改并不能反映我所有的组件,就像是从服务中复制了对象一样。

我所做的解决方案是将这个对象直接放入HTML文件this.userService.getUserModel()中,但是它太大了,我想避免这样做,只是为了一个好的语法。

问题是我如何才能对这个变量进行真正的引用,而不把这个服务方法直接放在我的组件上。


共2个答案

匿名用户

你可以尝试使用observable,然后订阅它。

例如:

public function getUserModel(): Observable<IUser> {
    return this.apiService.getUser(); // This is an observable
}

然后在您的组件上,而不是这样做:

this.userModel = this.userService.getUserModel();

您应该这样做:

this.userService.getUserModel().pipe(takeUntil(this._onDestroy$)).subscribe(user => {
    this.userModel = user;
}

指针

ondestroy$是在组件被破坏时取消订阅的一种非常简单的方法,有助于最大限度地减少内存泄漏。

因此您可以添加:

private _onDestroy$: Subject<any> = new Subject<any>();

然后在你的ngOnDestroy

ngOnDestroy() {
    this._onDestroy$.next();
    this._onDestroy$.complete();
}

因此,这应该会自动更新HTML中的值。

我希望这能帮上忙。

匿名用户

您可以创建一个EventEmitter,该EventEmitter在userModel每次更改时发出userModel。 然后,欧盟会在类上看到你想要得到的通知,并订阅这些变化。 像这样。

class UserService {
  userModelEvent: EventEmitter<UserModel> = new EventEmitter();
}

class AnotherClass {
  userModel: UserModel;

  constructor(userService: UserService) {}

  onInit() {
    this.userService.userModelEvent.subscribe(userModel => this.userModel = userModel);
  }
}