将Observable类型添加到TypeScript接口

时间:2017-02-07 23:55:29

标签: angular typescript

我想创建一个这样的TypeScript接口:

declare namespace UserService {

    interface IUserService {
        // Error: "Observable" can't be found
        getUsers(): Observable<Array<UserService.IUser>>;
    }

    interface IUser {
        Id: number;
        FirstName: string;
        LastName: string;
    }
}

...然后像这样使用它

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'

@Injectable()
export class UserService implements UserService.IUserService {

    private usersUrl = 'http://localhost:12345/api/users';

    constructor(private http: Http) {}

    public getUsers(): Observable<Array<UserService.IUser>> {
        return this.http.get(this.usersUrl).map(response => response.json() as Array<UserService.IUser>);
    }
}

问题是找不到Observable中的IUserService类型。如果我使用Promises并使用Promise作为类型,则会找到Promise类型,但我想使用Observable

我有可能在想这个错误。我会接受一个解决方案或替代方案。

谢谢

1 个答案:

答案 0 :(得分:1)

为什么不拥有你的界面:

interface IUser {
    Id: number;
    FirstName: string;
    LastName: string;
}

并在您的服务中指定它将返回一个Observable Array。

public getUsers(): Observable<IUser[]> { // will return Observable!
    return this.http.get(this.usersUrl).map(response => response.json());
}

这将返回一个Observable of IUser Array :)

然后从<:p>中删除implements

export class UserService implements UserService.IUserService {

只是:

export class UserService  {