我有一种方法可以根据请求url返回一个对象或一个包含相同对象的数组。逻辑很简单;在Typescript中返回多种Observable类型
myservice.service.ts:
private _url_User = "https://api.github.com/users/dummyuser";
constructor(private _http: Http){}
getUsers(followers?: boolean): Observable<User | User[]>{
this._url_User += followers?"/followers":"";//if followers equals true edit url, this returns array of same user object
return this._http.get(this._url_User).map(res=>res.json());
}
mycomponent.component.ts:
import { Component,OnInit } from '@angular/core';
import {Auth} from '../../services/auth.service';
import {CommentService} from '../../services/comment.service';
import {User} from '../../infrastructure/user';
@Component({
moduleId:module.id,
selector: 'app-comment',
templateUrl: '../../templates/comment.component.html'
})
export class CommentComponent implements OnInit{
user:User;
followers:User[];
constructor(private auth: Auth, private commentService: CommentService){
}
ngOnInit(){
this.commentService.getUsers().subscribe(d=>{ this.user=d[0]; console.log(this.user.email)});
this.commentService.getUsers(true).subscribe(d=>{this.followers=d; console.log(this.followers[0].email)});
}
}
该工作示例似乎并未编译:“类型'字符串'不可分配为键入'string []'”。 – spottedmahn
@spottedmahn这是故意的 - 请注意代码中的注释在底部调用这个函数,将示例分为'All Valid'(应该编译)和'Invalid'(各种不适用的示例,不应该) –
哦,对不起,我没有读得够近。我刚打开这个例子并点击运行!谢谢澄清! – spottedmahn