简体   繁体   中英

How do i get my code to return the result on time

I have this function, I am trying to get favorite movies, from a particular end point, Using angular. After getting all the movie list, from inside a class method, when I try to consume the list, I see that the list is not available.

This is what i have tried.

    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)
         }   
      }

I really don't understand the flow of the programme, I thought that the movieList property as been set when the function getMovies() was called but the local variable chosenMovie is not getting the desired value. Please any explanation on this behaviour?

You should wait for the response before you utilize the moviesList. Modify the function as below so that you process the response after it is received.

      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)
            })
      }

You are doing it wrong by assigning this.moviesList value to response obtained after http call by doing: 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)
       }

Since the movieList is empty, it will return empty response and hence no result.

You should return the response in subscribe block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM