【问题标题】:Angular: Return string from http RequestAngular:从http请求返回字符串
【发布时间】:2020-07-04 18:21:45
【问题描述】:

我有一个带有“电影”模型的 API。这部电影与一个流派相关联。当我从 API 获取电影时,我将流派的 url 作为“流派”属性获取。 在我的代码中,我正在创建这样的电影:

fetchMovies(token: string){

    this.httpOptions = {
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json',
      })
    };

    return this.http.get<{[key: string]: MovieData}>(this.url, this.httpOptions).pipe(
      map(res => {
        const movies = [];
        for (const key in res) {
          if (res.hasOwnProperty(key)) {
            movies.push(
              new Movie(
                key,
                res[key].title,
                res[key].desc,
                res[key].year,
                this.getGenre(res[key], res[key].genre),
                res[key].thumbnail,
                res[key].movie,
                res[key].createdUser,
                res[key].premium));
          }
        }
        return movies;
      }),
      tap(movies => {
        this._movies = movies;
      })
    );
  }

getGenre() 方法应该将流派作为字符串返回。

我尝试了以下方法:

getGenre(key, url): string{
      let result;
      this.http.get(url, this.httpOptions).subscribe(
        (res: any) => {
          result = res.title;
        }
      );
      return result;
    }

我怎样才能做到这一点?

我愿意接受任何想法。

【问题讨论】:

    标签: angular ionic-framework rxjs


    【解决方案1】:

    这是关于 Typescript 类的教程: https://www.typescriptlang.org/docs/handbook/classes.html。您将需要创建一个可以调用的方法。

    我一直在 Ionic 项目中使用类,以便我的 API 响应是强类型的。

    这是一个例子

    class Movie
    {
      ID:number;
      Title:string;
      Genre:string
      constructor(myMovie?:Partial<Movie>)
      {
        Object.assign(this,myMovie);
      }
      getGenre()
      {
        return this.Genre;
      }
    }
    

    您可以通过在每个动词(GET、POST)之前添加强类型 HTTP 响应并将响应投射到 then 块中。

    【讨论】:

      【解决方案2】:

      在使用httpClient的角度,你必须将responseType设置为文本

      getGenre() {
       return this.http.get(url, { responseType: 'text' });
      }
      

      但是你仍然需要订阅它来获取字符串值

      firstCall.pipe(
       switchMap((res) => {
        return combineLatest(this.getGenre(res[key], res[key].genre), of(res))
       })
      ).subscribe(([genre, data]) => {
          new Movie(
           key,
           data[key].title,
           data[key].desc,
           data[key].year,
           genre,
           data[key].thumbnail,
           data[key].movie,
           data[key].createdUser,
           data[key].premium));
      })
      

      【讨论】:

      • 从哪里得到“res”也是一个http调用吗?
      • 对不起,我没有完全理解。我用整个代码更新了我的问题。你能用它吗?
      猜你喜欢
      • 2019-03-30
      • 2018-09-19
      • 2023-04-09
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多