示例:
import { Injectable, ChangeDetectorRef } from '@angular/core';
@Injectable()
export class MyService {
constructor(private cdRef: ChangeDetectorRef) {}
updateComponent() {
// Do something that updates the HTML element
this.cdRef.detectChanges(); // Call detectChanges() to update the view
}
}
示例: 在服务中定义一个BehaviorSubject对象:
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class MyService {
private dataSubject = new BehaviorSubject(null);
data$ = this.dataSubject.asObservable();
updateData(data: any) {
this.dataSubject.next(data); // Push data changes to subscribers
}
}
在组件中订阅该服务的数据:
import { Component, OnInit } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-my-component',
template: `
{{ data }}
`
})
export class MyComponent implements OnInit {
data: any;
constructor(private myService: MyService) {}
ngOnInit() {
this.myService.data$.subscribe(data => {
this.data = data; // Update component view with new data
});
}
}