[英]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.