可能的原因是服务中的数据更改后,组件并没有及时获取到最新的数据。在这种情况下,您需要使用Observable来实现数据的动态更新。
首先,在服务中定义一个Subject,并将数据存储在其中:
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private dataSubject = new Subject
setData(data: any) { this.dataSubject.next(data); } }
然后,在组件中订阅Observable以获取最新的数据:
import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service';
@Component({ selector: 'app-component', templateUrl: './component.component.html', styleUrls: ['./component.component.css'] }) export class ComponentComponent implements OnInit { data: any;
constructor(private dataService: DataService) { }
ngOnInit() { this.dataService.dataObservable.subscribe(data => { this.data = data; }); } }
现在,每当服务中的数据更改时,组件将会自动获取到最新的数据。