In principle I want to tell you that I tried 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 the requests so that I can use them in my component and extract data from the artist, which works within a specific component. Now, once I navigate from one page to another that data obviously "flies" as the component is recreated. To solve this I decided to create another service which saves the JSON data in objects. I really don't know what I'm doing wrong though as I keep getting them as "undefened" in my other component. Although the data in the service is persistent... Thank you very much in advance!
// 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; } }
The component lifecycle in Angular doesn't apply to services: your problem is that the ngOnInit() method is never going to be called.
If you want to cache the data, you can simply save it after the first call, doing something like: