【问题标题】:How do i get my code to return the result on time我如何让我的代码按时返回结果
【发布时间】:2019-10-31 11:41:06
【问题描述】:

我有这个功能,我想从一个特定的端点获取最喜欢的电影,使用 angular。从类方法中获取所有电影列表后,当我尝试使用该列表时,我看到该列表不可用。

这是我尝试过的。

    import { Injectable } from '@angular/core';
    import {HttpClient} from '@angular/common/http'
    import {Observable} from 'rxjs'
    import { map, tap } from 'rxjs/operators';
    import { IMovie } from './welcome/welcome-page/movies-model';

    @Injectable({
      providedIn: 'root'
    })
     export class FavoriteMoviesService {
        movieList: IMovie[];
        constructor(private _http: HttpClient) {
      }

      getFavMovies(id: number) {
        let getMovies = () => {
          return this._http.get('../assets/movies.json').pipe(
          tap(response => console.log(response))
          ).subscribe(response => response = this.movieList)
       }
         getMovies();
         let chosenMovie = this.movieList? this.movieList.find(movie => movie.id == id): Array(null)
         console.log(chosenMovie)
         }   
      }

我真的不明白程序的流程,我认为在调用函数 getMovies() 时设置了 movieList 属性,但局部变量 selectedMovie 没有获得所需的值。 请对此行为进行任何解释?

【问题讨论】:

  • 您的getMovies 函数是异步的,而您的chosenMovie 同步执行,无需等待getMovies 完成。因此你得到chosenMovieempty
  • 你正在丢弃响应,将.subscribe(response => response = this.movieList)更改为.subscribe(response => this.movieList = response)

标签: javascript angular rxjs observable


【解决方案1】:

在使用电影列表之前,您应该等待响应。修改如下函数,以便在收到响应后处理它。

      getFavMovies(id: number) {
        this._http.get('../assets/movies.json').pipe(
          tap(response => console.log(response))
          ).subscribe(response => {
              this.movieList = response;
              let chosenMovie = this.movieList? this.movieList.find(movie => movie.id == id): Array(null);
              console.log(chosenMovie)
            })
      }

【讨论】:

  • 有了这个,我的意思是我要在订阅体上写一大堆代码
【解决方案2】:

this.moviesList 值分配给在http 调用后获得的response 这样做是错误的:response = this.movieList:

let getMovies = () => {
          return this._http.get('../assets/movies.json').pipe(
          tap(response => console.log(response))
          ).subscribe(response => this.moviesList = response.data; // whatever is your object for movielist)
       }

由于movieList 为空,它会返回空响​​应,因此没有结果。

您应该在订阅块中返回response

【讨论】:

  • 我确实返回了响应,但是我如何获取值以便使用它。
  • 当我返回响应并将函数分配给一个变量并在控制台上注销该值时,我得到了一个看起来与我预期的数据完全不同的奇怪对象。这就是我得到的:订阅者{关闭:false,_parent:null,_parents:null,_subscriptions:Array(1),syncErrorValue:null,...}
  • 您可以检查响应值并从中获取所需的对象并将其分配给this.moviesList
猜你喜欢
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
相关资源
最近更新 更多