在订阅时使用take(1)
来确保只调用一次API。
以下是示例代码:
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent implements OnInit {
data;
constructor(private apiService: ApiService) { }
ngOnInit() {
this.apiService.getData()
.take(1)
.subscribe(data => {
this.data = data;
});
}
}