要实现在两个路由/视图中只从API获取数据一次并显示,可以使用Angular的服务和路由解决方案。
首先,创建一个数据服务来处理API请求和数据存储:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
private dataSubject = new BehaviorSubject(null);
public data$: Observable = this.dataSubject.asObservable();
constructor(private http: HttpClient) { }
getData(): Observable {
if (this.dataSubject.value) {
return this.data$; // 如果已有数据,则直接返回
} else {
return this.http.get('your-api-url').pipe(
tap(data => this.dataSubject.next(data))
);
}
}
}
然后,在两个要显示数据的组件中注入数据服务,并在需要数据的地方订阅数据:
import { Component, OnInit } from '@angular/core';
import { DataService } from 'your-data-service';
@Component({
selector: 'app-component1',
template: `
{{ data }}
`
})
export class Component1 implements OnInit {
data: any;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.data = data;
});
}
}
import { Component, OnInit } from '@angular/core';
import { DataService } from 'your-data-service';
@Component({
selector: 'app-component2',
template: `
{{ data }}
`
})
export class Component2 implements OnInit {
data: any;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.data = data;
});
}
}
这样,无论在哪个路由/视图中,只要数据已经通过API获取并存储,就不会再次发出API请求,而是直接使用已经获取的数据。