簡體   English   中英

Angular2上的異步函數

[英]Async functions on Angular2

我想使此服務上的函數異步,最后一個函數應等待上面的響應,依此類推。 我在createPlaylist()的第二行上收到“類型為void的屬性訂閱不存在”,我不知道為什么。

進口:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';

碼:

getUserId(token:string = localStorage.getItem('myToken')) {
  const url = 'https://api.spotify.com/v1/me';
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  this.http.get(url, {headers : headers}).map((res: Response) => res.json())
  .subscribe(result => {
    this.currentUser = result.id;
    console.log(this.currentUser);
    return Observable.of(result);
  });
}

createPlaylist(token:string = localStorage.getItem('myToken')) {
  this.getUserId().subscribe(user => {
  const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists`;
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  headers.append('Content-Type', 'application/json');
  const body = {
    'name': 'searchDDD playlist'
  };
  this.http.post(url, body, { headers } )
  .subscribe(result => {
    console.log(result.json().name);
    console.log(result.status);
    this.playlistID = result.json().id;
  });
  });
}

addSongs(token:string = localStorage.getItem('myToken')) {
  this.createPlaylist();
  const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists/${this.playlistID}/tracks`;
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  headers.append('Content-Type', 'application/json');
  const body = {'uris': ['spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
  'spotify:track:1301WleyT98MSxVHPZCA6M']};
  this.http.post(url, body, { headers } )
  .subscribe(result => {
    console.log(result.status);
  });
}

getUserId函數返回並刪除預訂部分。 您可以一次訂閱一個Observable並將邏輯放入單個subscribe也可以只通過do函數編寫一個中間邏輯。

getUserId(token:string = localStorage.getItem('myToken')) {
  const url = 'https://api.spotify.com/v1/me';
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  return this.http.get(url, {headers : headers})
                  .map((res: Response) => res.json())
                  .do(result => this.currentUser = result.id);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM