Pass objects from a Service to Components

2

At first I want to tell you to try several ways but they did not work. It is an application that uses the Spotify backend, and for this I have a service which handles requests so you can use in my component and extract data from the artist, which works within a specific component. Now, once I navigate from one page to another, those data obviously "fly" as the component is recreated. To solve this, I decided to create another service which saves me the JSON data in objects. However, I do not really know what I'm missing since I keep getting them as "undefened" in my other component. Even though the data in the service is persistent ... Thank you very much!

// artist.service.ts

import { OnInit, Injectable } from '@angular/core';
import { SpotifyService } from './spotify.service';
import { ActivatedRoute } from '@angular/router';

@Injectable()
export class ArtistService implements OnInit {

    artist: any = {};
    tracks: any = [];
    albums: any = [];
    artistRel: any = {};

    constructor(private _spotify: SpotifyService, public route: ActivatedRoute) {}

    ngOnInit() {
        this.route.params.map(params => params['id'])
      .subscribe(id => {
        this._spotify.getArtista(id)
          .subscribe(artist => {
            console.log(artist, 'Artista');
            this.artist = artist;
          });
        this._spotify.getTop(id)
            .map( (resp: any) => resp.tracks)
              .subscribe( tracks => {
                console.log(tracks, 'Pistas');
                this.tracks = tracks;
          });
        this._spotify.getAlbumsArtist(id)
            .map( (resp: any) => resp.items)
              .subscribe( albums => {
                console.log(albums, 'Albums');
                this.albums = albums;
          });
        this._spotify.getRelatedArtists(id)
            .map( (resp:any) => resp)
              .subscribe( related => {
                console.log(related, 'Artistas relacionados');
                this.artistRel = related;
          });
      });
    }
}

    // artist.component.ts

    import { Component, OnInit } from '@angular/core'; 
    import { ActivatedRoute, Data } from '@angular/router'; 
    import { ArtistService } from '../../services/artist.service';

    @Component({   
      selector: 'app-artist',   
      templateUrl: './artist.component.html' })

   export class ArtistComponent implements OnInit {

      artist: any = {};


      constructor(private route: ActivatedRoute, public _artist: ArtistService){}

      ngOnInit() {
        this.artist = this._artist.artist;  } }
    
asked by Nacho 25.04.2018 в 06:16
source

1 answer

0

The life cycle of the components in Angular does not apply to services: your problem is that the ngOnInit () method will never be called.

If you want to cache the data, you can simply save it after the first call, doing something like:

// artist.service.ts

import { OnInit, Injectable } from '@angular/core';
import { SpotifyService } from './spotify.service';
import { ActivatedRoute } from '@angular/router';

@Injectable()
export class ArtistService {

  artist: any = {};
  tracks: any = [];
  albums: any = [];
  artistRel: any = {};

  constructor(private _spotify: SpotifyService) {}
    
  getArtista(id): Observable<any> {
    if (this.artist) {
      return Observable.of(this.artist);
    }
    return this._spotify.getArtista(id).do(artist => {
      console.log(artist, 'Artista');
      this.artist = artist;
    });
  }
  
  //otros métodos
}
    
answered by 25.04.2018 / 09:47
source