- 确认 API 接口地址是否正确且能够访问。
- 确认 API 接口返回的数据格式是否为 JSON 格式。
- 使用 Angular 的 HttpClient 模块发送 HTTP 请求,并在订阅时使用 map 方法将响应数据转换为 JSON 对象。
示例代码如下:
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
getPosts(): Observable {
return this.http.get('https://jsonplaceholder.typicode.com/posts')
.pipe(map(response => response.json()));
}
}