Angular 参考组件';服务中的嵌套变量,反之亦然

Angular 参考组件';服务中的嵌套变量,反之亦然,angular,typescript,service,rxjs,angular6,Angular,Typescript,Service,Rxjs,Angular6,在Angular 6中,我想从我的服务访问组件的嵌套(本地,函数内部)变量 myComponent.ts myFunction() { var componentArray = []; } myServiceFunction() { if (errorExists) { componentArray.push("error exists!"); //how can I do this? } } myService.ts myFunction() { va

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

myComponent.ts

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

myService.ts

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

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

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

服务将公开一个可观察对象,该对象在发生错误时发出错误消息,组件将订阅以接收这些消息

您必须决定这应该是主题、行为主题还是重播主题。取决于你的需要,但这里我只使用一个主题

@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");
       }
    }
}
@Injectable()
导出类MyService{
私有_错误:主题=新主题();
public getErrors():可观察的{
返回此项。_errors.asObservable();
}
公共职能(){
如果(存在错误){
这是错误。下一步(“错误存在”);
}
}
}
然后,组件将侦听这些错误,并将它们添加到数组中

@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);
       });
   }
}
@组件({…})
导出类MyComponent实现OnDestroy,OnInit{
私有组件数组=[];
private readonly _$:Subject=new Subject();
公共构造函数(私有myService:myService){}
公共恩格德斯特罗(){
这个。_销毁了$.next();
此._销毁了$.complete();
}
公共ngOnInit(){
常量函数=[];
这个.myService.getErrors()管道(
takeUntil(这个.\u美元)
).subscribe(错误=>{
this.componentArray.push(错误);
功能推送(错误);
});
}
}
将值添加到数组后,如何使用该值取决于您。如果修改模板中使用的零部件特性,则需要将视图标记为脏视图,以通知需要进行更改检测


顺便说一句,我意识到这个问题从根本上讲有很多错误。我今天只是有一个yuge brain放屁…你不能。你不应该从服务中访问组件变量,你应该用其他方式。从component@MadhawaPriyashantha,谢谢-我想可能是这样的。假设情况相反,我想从我的组件访问服务的嵌套变量-这可能吗?不,仍然不可能。无法从外部访问局部变量。