在Angular 8中,如果行为主题在服务中不发出下一个值,可能是因为订阅者未正确订阅该主题。以下是一个解决方法,其中包含一个代码示例:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private dataSubject = new BehaviorSubject('initial value');
public data$ = this.dataSubject.asObservable();
constructor() { }
updateData(value: string) {
this.dataSubject.next(value);
}
}
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-my-component',
template: `
{{ data }}
`
})
export class MyComponent implements OnInit {
data: string;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.data$.subscribe((value) => {
this.data = value;
});
}
}
确保在组件的ngOnInit
生命周期钩子中订阅主题。这样,当主题中有新值时,组件将接收到并更新相应的数据。
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-another-component',
template: `
`
})
export class AnotherComponent {
constructor(private dataService: DataService) { }
updateData() {
this.dataService.updateData('new value');
}
}
在组件中调用服务的updateData
方法,可以更新主题中的值。这将触发主题的next
方法,将新值发出给所有订阅者。
确保在调用updateData
方法之前已经正确注入了DataService
。