[在Angular中使用fetch或http get方法时无法从API获取数据

问题描述 投票:0回答:1

我正在尝试使用提取方法从此api提取数据

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse} from '@angular/common/http';
import { throwError, Observable, from} from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})

export class ApiService {


 private SERVER_URL = 'https://bpdts-test-app.herokuapp.com/city/London/users';
constructor(private httpClient: HttpClient) { }

  getData(): Observable<any> {
    return from(
      fetch(
        'https://bpdts-test-app.herokuapp.com/city/London/users', // the url that i am are trying to access
        {
          headers: {
            'Content-Type': 'application/json',
          },
          method: 'GET', // GET, POST, PUT, DELETE
          mode: 'no-cors' // the most important option
        }
      ));

      }}

然后我正在尝试订阅这样的数据

ngOnInit() {

 this.apiService.getData().subscribe((data: any[]) => {
 console.log(data);

但是我收到的回应是空的“清空响应,单击此处”“>

我也尝试过httpClient get方法,这在下面给了我CORS问题,并且我无法控制服务器后端,因此我无法更改CORS。有人可以帮助我尝试过此处Angular Proxy中所述的CORS解决方案,但没有任何区别。

export class ApiService {
 private SERVER_URL = 'https://bpdts-test-app.herokuapp.com/city/London/users';
constructor(private httpClient: HttpClient) { }

public fetchData() {
return this.httpClient.get(`${this.SERVER_URL}`)
}

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS91UkNWRi5wbmcifQ==” alt =“使用第二种方法出现错误。”>

我正在尝试使用从'@ angular / core'导入方法import {Injectable}从此api获取数据;从'@ angular / common / http'导入{HttpClient,HttpErrorResponse}; import {throwError,...

javascript json angular api httpclient
1个回答
0
投票

例如,您必须创建一个定义用户属性的模型:

© www.soinside.com 2019 - 2024. All rights reserved.