2016-11-28 57 views
1

我有一种方法可以根据请求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)}); 
    } 
} 

,这里是错误消息我想不出手柄; enter image description here

回答

4

一般来说,我建议做的实际上是将它分成两个方法,而不是使用布尔标志。这将更简单,更清晰,并且也将免费解决您的打字问题。

如果你真的不想这样做,那么你会想为你的方法添加function overload。通过这些,你可以告诉TypeScript这个函数总是返回一个标志设置为false的单个用户,或者如果标志设置为true,那么许多用户会返回你正在查找的行为。

此功能的过载会是这个样子:

getUsers(): Observable<User>; 
getUsers(followers: false): Observable<User>; 
getUsers(followers: true): Observable<User[]>; 
getUsers(followers?: boolean): Observable<User | User[]>{ 
    this._url_User += followers?"/followers":""; 
    return this._http.get(this._url_User).map(res=>res.json()); 
} 

我已经把a working example在操场上,如果你想看到什么这一切的样子。

请注意,这确实保留了它仍然存在的潜在歧义。即如果您使用布尔值调用getUsers,并且在编译时TypeScript不知道它是true还是false,它仍然会返回Observable<User | User[]>。您必须使用任何类型断言或类型警卫来获取正确的类型 - 如果您不熟悉这些内容,请查阅手册中的Type Guards and Differentiating Types部分。

+0

该工作示例似乎并未编译:“类型'字符串'不可分配为键入'string []'”。 – spottedmahn

+0

@spottedmahn这是故意的 - 请注意代码中的注释在底部调用这个函数,将示例分为'All Valid'(应该编译)和'Invalid'(各种不适用的示例,不应该) –

+0

哦,对不起,我没有读得够近。我刚打开这个例子并点击运行!谢谢澄清! – spottedmahn

相关问题