要解决Angular插值错误并从API获取数据失败,可以按照以下步骤进行:
import { HttpClient } from '@angular/common/http';
import { catchError, map } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class DataService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('api/data') // 替换为你的API地址
.pipe(
map(response => response),
catchError(error => throwError('获取数据失败'))
);
}
}
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
template: `
正在加载...
{{errorMessage}}
{{data}}
`
})
export class AppComponent {
isLoading = false;
errorMessage = '';
data: any;
constructor(private dataService: DataService) {}
ngOnInit() {
this.isLoading = true;
this.dataService.getData().subscribe(
data => {
this.isLoading = false;
this.data = data;
},
error => {
this.isLoading = false;
this.errorMessage = error;
}
);
}
}
{{data}}
这样,当从API获取数据失败时,将会显示"获取数据失败"的错误消息,并且数据加载时会显示"正在加载..."的消息。