如何在angular14的httpClient方法中更新数组值



尝试使用httpClient方法更新数组值。但不能正常工作。如何在httpclient方法之外获得更新的数组值。如果有人知道,请帮助找到解决方案。

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
}

Demo: https://stackblitz.com/edit/angular-ivy-zpvafg?file=src%2Fapp%2Fapp.component.ts

您应该在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
});


}

您的组件不应该处理任何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));
}
}

或者让模板HTML在必要时使用async管道来处理响应:

@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

最新更新