简体   繁体   中英

Angular 2+ and storing data in variable from http in service

I have getPrivateLesson() in my service, that returns the array of objects. How to run that function in service (once, on initialization) and store returned data in variable filteredPrivateLessons? I tried with subject and constructor but without positive effect.

@Injectable()
export class PrivateLessonsService {

  private _privateLessonsUrl: string = "http://localhost:3000/api/lessons";
  public filteredPrivateLessons: PrivateLesson[];
  public filteredPrivateLessonsUpdate = new EventEmitter<PrivateLesson[]>();

  private privateLessonsSubject = new Subject<any>()
  public privateLessonsChange$ = this.privateLessonsSubject.asObservable();


  constructor(private _http: Http,  private _httpClient: HttpClient) {

    this.privateLessonsChange$.subscribe(response => {
      this.filteredPrivateLessons = this.getPrivateLessons();
    });

  }

  getPrivateLessons() : any {
    return this._http.get(this._privateLessonsUrl)
      .map( (response: Response) => response.json() );    
  }

  getFilteredPrivateLessons() {
    return this.filteredPrivateLessons;
  }
  setFilteredPrivateLessons(privateLessons: PrivateLesson[]) {
    this.filteredPrivateLessons = privateLessons;
    this.filteredPrivateLessonsUpdate.emit(this.filteredPrivateLessons);
  }

}

You can inject this service in you app.component and call the function like so:

app.component.ts :

    ngOnInit(){
        this._privateLessonsService.getPrivateLessons().subscribe(
        success =>{
          this._privateLessonsService.filteredPrivateLessons = success;
        },
        error =>{
          //Handle error here
        }
      );
    } 

You can then assume in the rest of your app that the array is ready and stored within your service object. Where you need to read it, inject the service and you will have access to it like so :

this._privateLessonsService.filteredPrivateLessons

No Need for a subject here as you don't need to perform an action following the change of that array. You only need to download it once and have access to it!

Per comments from @Rahul Gupta editing the answer.

@OP- If you are not able to assign the response value to the variable, you can try adding an anonymous function to use this asynchronously.

I am not sure how do you want to use this on your component but now your variable should have the response value. Another way could be to move subscriber to your component(though i am not sure how your requirement is)

Editing my earlier response to add anon function.

this.getPrivateLessons().subscribe(response => {
      this.filteredPrivateLessons = res;
   },
   () => {
        console.log(this.filteredPrivateLessons);
    });
}

getPrivateLessons() : any {
   return this._http.get(this._privateLessonsUrl)
      .map( (response: Response) => response.json() );    
}

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