Angular2上的异步函数

时间:2017-11-14 06:13:42

标签: javascript angular typescript web

我想让这个服务上的函数异步,最后一个函数应该等到它上面的一个响应,依此类推。我得到'属性订阅不存在类型void'在createPlaylist()的第二行,我不知道为什么。

进口:

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);
  });
}

1 个答案:

答案 0 :(得分:2)

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);
}