尝试使用httpClient方法更新数组值。但工作不正常。如何在httpclient method.If之外获取更新的数组值,任何人都知道,请帮助找到解决方案。
app.component.ts:
public allData = ['Van1', 'Hills2', 'Root3'];
constructor(private httpClient: HttpClient) {}
ngOnInit(): void {
this.httpClient.get<string[]>('../assets/data.json').subscribe((data) => {
this.allData = data;
});
console.log(this.allData); // it should be data.json data
}演示:https://stackblitz.com/edit/angular-ivy-zpvafg?file=src%2Fapp%2Fapp.component.ts
发布于 2022-07-12 14:18:42
您应该在httpClient订阅中打印控制台日志。尝试这个,您将得到更新的数据。
ngOnInit(): void {
this.httpClient.get<string[]>('../assets/data.json').subscribe((data) => {
this.allData = data;
console.log(this.allData); // it should be data.json data
});
}发布于 2022-07-12 14:24:09
组件不应该处理任何http请求,为此,需要使用service。
@Injectable({...})
export class MyService {
constructor(private http: HttpClient) {}
getData(): Observable<string[]> {
return this.http.get<string[]>('../assets/data.json');
}
}然后,在组件中,为了获得更新的数据列表,可以在组件中订阅:
@Component({...})
export class MyComponent implements OnInit {
constructor(private myService: MyService){}
ngOnInit(): void {
this.myService.getData().subscribe(data => console.log('Response: ', data));
}
}或者,如果需要使用async管道来处理响应,可以使用模板HTML:
@Component({...})
export class MyComponent implements OnInit {
theDataFromTheBackend$!: Observable<string[]>;
constructor(private myService: MyService){}
ngOnInit(): void {
this.theDataFromTheBackend$ = this.myService.getData();
}
}<ng-container *ngIf="theDataFromTheBackend$ | async as result">
<div> {{ result | json }} </div>
</ng-container>此外,当您订阅任何可观察到的代码时,这段代码将在稍后执行,因为是asynchronous。
someFunction(): void {
console.log(1);
this.myservice.getData().subscribe(console.log(2));
console.log(3);
}以上输出为1,3,2。
https://stackoverflow.com/questions/72953437
复制相似问题