[英]Async functions on Angular2
I want to make functions on this service asynchronous, the last function should wait to a response of the one above it and so on. 我想使此服务上的函数异步,最后一个函数应等待上面的响应,依此类推。 I am getting 'property subscribe does not exist on type void' on the second line of createPlaylist() and I don't know why.
我在createPlaylist()的第二行上收到“类型为void的属性订阅不存在”,我不知道为什么。
Imports: 进口:
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';
Code: 码:
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);
});
}
Return from the getUserId
function and remove the subscribe part. 从
getUserId
函数返回并删除预订部分。 You can just one time subscribe to a Observable and put the logic inside the single subscribe
or just write an intermediate logic via do
function. 您可以一次订阅一个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.