在愉快地与AngularJS 1合作之后,我目前正在try 自学Angular2和打字脚本.*在过go 的四年里!我不得不承认我讨厌它,但我相信我的尤里卡时刻就在眼前...无论如何,我已经在我的虚拟应用程序中编写了一个服务,该服务将从我编写的提供JSON服务的假后端获取http数据.
import {Injectable} from 'angular2/core';
import {Http, Headers, Response} from 'angular2/http';
import {Observable} from 'rxjs';
@Injectable()
export class UserData {
constructor(public http: Http) {
}
getUserStatus(): any {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get('/restservice/userstatus', {headers: headers})
.map((data: any) => data.json())
.catch(this.handleError);
}
getUserInfo(): any {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get('/restservice/profile/info', {headers: headers})
.map((data: any) => data.json())
.catch(this.handleError);
}
getUserPhotos(myId): any {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get(`restservice/profile/pictures/overview/${ myId }`, {headers: headers})
.map((data: any) => data.json())
.catch(this.handleError);
}
private handleError(error: Response) {
// just logging to the console for now...
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
现在在一个组件中,我希望同时运行(或链接)getUserInfo()
和getUserPhotos(myId)
个方法.在AngularJS中,这很容易,因为在我的控制器中,我会这样做以避免"末日 pyramid "...
// Good old AngularJS 1.*
UserData.getUserInfo().then(function(resp) {
return UserData.getUserPhotos(resp.UserId);
}).then(function (resp) {
// do more stuff...
});
现在我试着在我的组件中做一些类似的事情(用.subscribe
替换.then
),但是我的错误控制台快疯了!
@Component({
selector: 'profile',
template: require('app/components/profile/profile.html'),
providers: [],
directives: [],
pipes: []
})
export class Profile implements OnInit {
userPhotos: any;
userInfo: any;
// UserData is my service
constructor(private userData: UserData) {
}
ngOnInit() {
// I need to pass my own ID here...
this.userData.getUserPhotos('123456') // ToDo: Get this from parent or UserData Service
.subscribe(
(data) => {
this.userPhotos = data;
}
).getUserInfo().subscribe(
(data) => {
this.userInfo = data;
});
}
}
我显然做错了什么...如何最好地使用Observable和RXJ?抱歉,如果我问了一些愚蠢的问题...但是提前谢谢你的帮助!我还注意到,在声明http头时,函数中重复了代码...