获取组件的持久数据

时间:2018-05-04 06:22:20

标签: angular typescript

我想知道我做错了什么因为我需要来自服务的持久数据并在我的艺术家和专辑组件上获取数据。我不粘贴相册组件'因为它是相同的。我试图获得艺术家,专辑,曲目等...我很抱歉,如果这是一个基本的问题,但我是角度和打字稿的新。感谢您随时阅读!。

// artist.service.ts

import { Injectable } from '@angular/core';
import { SpotifyService } from './spotify.service';
import { Observable } from 'rxjs';

@Injectable()
export class ArtistService {

     artist: any;
     tracks: any;
     albums: any;
     artistRel: any;

    constructor(private _spotify: SpotifyService) {}

    getArtistDetail(id: string) {
        return new Promise((resolve, reject) => {
            resolve(this._spotify.getArtista(id).subscribe(artist => {
                console.log(artist, 'Artista');
                return this.artist = artist;
            }));
        }).then(resp => {
            this._spotify.getTop(id).map((resp:any) => resp.tracks)
                .subscribe(tracks => {
                    console.log(tracks, 'Tracks');
                        return this.tracks = tracks;
                    });

        }).then(resp => {
            this._spotify.getAlbumsArtist(id).map((resp: any) => resp.items)
                .subscribe(albums => {
                    console.log(albums, 'Albums');
                    return this.albums = albums;
                });
        }).then(resp => {
            this._spotify.getRelatedArtists(id).map((resp: any) => resp)
                .subscribe(related => {
                    console.log(related, 'Artists related');
                    return this.artistRel = related;
                });
        }).catch(error => console.log(error, 'Something Happened...'));
    }

}
  

块引用

// artist.component.ts

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

@Component({
  selector: 'app-artist',
  templateUrl: './artist.component.html'
})
export class ArtistComponent implements OnInit {

  artist: {};

  constructor(public _artistService: ArtistService, private route: ActivatedRoute) {
    this.route.params.map(params => params['id']).subscribe(id => {
      this._artistService.getArtistDetail(id);
    });
  }

  ngOnInit() {
    // Im trying this way..but it doesn't work
    this.artist = this._artistService.artist;
  }
}
  

块引用

// artist.component.html

<div class="container top30" *ngIf="artist">
    <div class="row">
        <div class="col-md-3">
            <img [src]="artist.images | sinfoto" class="img-thumbnail  rounded-circle">

        </div>
        <div class="col-md-9">
            <h1>{{ artist.name }}</h1>
            <hr>

            <a [href]="artist.external_urls.spotify" target="_blank" class="btn btn-outline-success">Abrir Spotify</a>
            <button [routerLink]="['/search']" type="button" class="btn btn-outline-danger">Regresar</button>


        </div>


    </div>
<!-- Desplegar albumes -->
<div class="container top30">
    <div class="row">
        <div class="col-md-3"
             *ngFor="let album of albums">
             <img [src]="album.images | sinfoto" 
                  class="img-thumbnail puntero"
                  [routerLink]="['/album', album.id]"
                  >

             <p>{{ album.name }}</p>
        </div>

    </div>
</div>

2 个答案:

答案 0 :(得分:0)

您的问题似乎是代码的异步性质。在组件的构造函数中,您进行了异步调用以获取数据。接下来执行ngOnInit()函数,您尝试获取尚未存在的数据,因为尚未返回异步调用并设置结果。这一行

this.artist = this._artistService.artist;

将返回null,因为this._artistService.artist尚未通过异步调用设置为数据。

答案 1 :(得分:0)

你可以使用一个getter(所以,你不需要使用ngOnInit)

//artist{}  //<--comment this, use a getter
get artist()
{
    return this._artistService.artist
}

无论如何,你必须考虑使用Observables和你的服务返回Observables(或Promise),而不是存储数据

使用Observables,您的服务就像

getArtistDetail(id: string) {
     return forkJoin([
         this._spotify.getArtista(id),
         this._spotify.getAlbumsArtist(id),
         this._spotify.getRelatedArtists(id)])
}

在您的组件中

ngOnInit() {
    //I put the subscribe to params in ngOnInit

    this.route.params.map(params => params['id']).subscribe(id => {
      this._artistService.getArtistDetail(id).subscribe(res=>
      {  //res is an array
         console.log(res);
         this.artist=res[0];
         this.albums=res[1];
         this.related=res[2]; 
      })
    });
 }