【问题标题】:Reference a component's nested variable from a service, or vice versa从服务中引用组件的嵌套变量,反之亦然
【发布时间】:2019-07-31 00:38:35
【问题描述】:

Angular 6 中,我想从我的服务中访问组件的嵌套(本地,函数内部)变量。

myComponent.ts

myFunction() {
   var componentArray = [];
}


myService.ts

myServiceFunction() {
   if (errorExists) {
      componentArray.push("error exists!"); //how can I do this?
   }
}

这可能吗?我可以引用其他组件的全局属性或函数,但是在这些函数中访问局部变量呢?

【问题讨论】:

  • 顺便说一句,我意识到这个问题从根本上来说有很多问题。我今天只是放个屁而已……
  • 你不能。你不应该从服务访问组件变量你应该做其他方式。从组件访问服务
  • @MadhawaPriyashantha,谢谢-我认为可能是这种情况。假设场景颠倒了,我想从我的组件中访问服务的嵌套变量 - 这可能吗?
  • 不仍然不可能。局部变量无法从外部访问。

标签: angular typescript service rxjs angular6


【解决方案1】:

您可以使用订阅者模式在服务和组件之间进行通信。

服务会公开一个可观察对象,当错误消息发生时会发出错误消息,并且组件会订阅接收这些消息。

您必须决定这应该是主题、行为主题还是重播主题。根据您的需要,但这里我将只使用主题。

@Injectable()
export class MyService {
    private _errors: Subject<string> = new Subject();

    public getErrors(): Observable<string> { 
       return this._errors.asObservable();
    }

    public someFunction() {
       if(errorExists) {
          this._errors.next("error exists");
       }
    }
}

然后组件会监听这些错误,并将它们添加到数组中。

@Component({...})
export class MyComponent implement OnDestroy, OnInit {
   private componentArray = [];

   private readonly _destroyed$: Subject<void> = new Subject();

   public constructor(private myService: MyService) {}

   public ngOnDestroy() {
      this._destroyed$.next();
      this._destroyed$.complete();
   }

   public ngOnInit() {
       const functionArray = [];

       this.myService.getErrors().pipe(
           takeUntil(this._destroyed$)
       ).subscribe(error => {
           this.componentArray.push(error);
           functionArray.push(error);
       });
   }
}

将值添加到数组后如何使用它取决于您。如果您修改模板中使用的组件属性,则需要将视图标记为脏,以通知 Angular 需要进行更改检测。

https://angular.io/api/core/ChangeDetectorRef

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多