如何使用 Observable 从文件中获取 json 数据

Tom*_*int 9 json typescript angular

在使用此方法之前,我正在练习从 json 文件中读取数据,该文件包含国家和州的列表,但我想使用 httpClient 并且通过测试我有这些方法,但是读取此数据的正确方法是什么. 早期方法:

  getCountries(): Observable<Country[]> {
    return of(countries['countries']);
  }
  getStates(countryID): Observable<State[]> {
    return of(countries['states'].filter(f => f.countryId === countryID));
  }

Run Code Online (Sandbox Code Playgroud)

这是一种如何工作的方法:

  getC(): Observable<Country[]> {
    return this.http.get<Country[]>(this.link).pipe(map(k => {
      return k['countries'];
    }));
  }
  getS(CID): Observable<State[]> {
    return this.http.get<State[]>(this.link).pipe(map(v => {
      return v['states'].filter(f => f.countryId === CID);
    }));
  }
Run Code Online (Sandbox Code Playgroud)

我看到类似的东西,但我有错误

  getC3(): Observable<Country[]> {
    return this.http.get<Country[]>(this.link)
      .toPromise()
      .then(res => <Country[]>res.countries)
      .then(data => {return data});
    }
Run Code Online (Sandbox Code Playgroud)

正确的方法是如何做到这一点,错误:

舞会错误

已经几天了,好像问题比较严重,所以问这边,请问这个json获取数据的方法是什么:

  [
    {
      "data": [
        {
           "label": "Select State",
           "value": null
        },
        {
          "label": "Adeje",
          "value": {
             "county": "Gran Canaria",
             "state": "Islas Canarias",
             "country": "España"
           }
        },
        {
          "label": "Agaete",
          "value": {
            "county": "Gran Canaria",
            "state": "Islas Canarias",
            "country": "España"
         }
       }
     ]
   }
 ]
Run Code Online (Sandbox Code Playgroud)

以及如何从这个 json 获取数据:

[
  {
    "label": "Select State",
    "value": null
  },
  {
    "label": "Adeje",
    "value": {
      "county": "Gran Canaria",
      "state": "Islas Canarias",
      "country": "España"
    }
  },
  {
    "label": "Agaete",
    "value": {
      "county": "Gran Canaria",
      "state": "Islas Canarias",
      "country": "España"
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

考虑到我使用--strict模式

Owe*_*vin 7

解决问题的最简单方法是认识到使用 angular 时的最佳实践是使用Observables而不是使用Promises

问题

考虑代码

getC3(): Observable<Country[]> {
  return this.http.get<Country[]>(this.link)
    .toPromise()
    .then(res => <Country[]>res.countries)
    .then(data => {return data});
  }
Run Code Online (Sandbox Code Playgroud)

Thw 行将return this.http.get<Country[]>(this.link)返回一个Observable. 如果您调用.toPromise()an,Observable则返回一个Promise。因此,您将收到以下错误Promise<Country[]> does not contain properties ... from type Observable<Country[]>

解决方案

解决这个问题的一种方法(更好的方法)是简单地将类型保持为 Observable。

getC3(): Observable<Country[]> { return this.http.get<Country[]>(this.link)}
Run Code Online (Sandbox Code Playgroud)

我不会在下面推荐,将返回类型更改为 promise

getC3(): Promise<Country[]> {
  return this.http.get<Country[]>(this.link)
    .toPromise()
    .then(res => <Country[]>res.countries)
    .then(data => {return data});
  }
Run Code Online (Sandbox Code Playgroud)