[英]How reference a variable in Service on a local variable on component from a Angular Project?
[英]Reference a component's nested variable from a service, or vice versa
在Angular 6
,我想從我的服務中訪問組件的嵌套(局部,在函數內部)變量。
myComponent.ts
myFunction() {
var componentArray = [];
}
myService.ts
myServiceFunction() {
if (errorExists) {
componentArray.push("error exists!"); //how can I do this?
}
}
這可能嗎? 我可以引用其他組件的全局屬性或功能,但是如何訪問那些功能中的局部變量呢?
您可以使用訂戶模式在服務和組件之間進行通信。
該服務將公開一個可觀察對象,該對象在發生錯誤時會發出錯誤消息,並且組件將訂閱以接收那些消息。
您必須決定這應該是Subject,BehaviorSubject還是ReplaySubject。 根據您的需要,但是在這里我僅使用一個主題。
@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需要進行更改檢測。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.