我有一種方法可以根據請求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