5

I would like to make a TypeScript interface like this:

declare namespace UserService {

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

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

...and then use it like this

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>);
    }
}

The problem is that the Observable type in the IUserService isn't found. If I use Promises and use Promise as the type then the Promise type is found but I want to use Observable.

It is possible I'm thinking about this wrong. I will accept a solution or an alternative.

Thank you

2
  • Have you got import { Observable } from 'rxjs/Observable'; before the declare namespace UserService {? Commented Feb 8, 2017 at 2:08
  • @TuongLe Imports like this in an interface don't work. Commented Feb 8, 2017 at 15:45

1 Answer 1

6

Why not just have your interface:

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

and in your service you specify that it will return an Observable Array.

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

This will return a Observable of IUser Array :)

Also then remove the implements from:

export class UserService implements UserService.IUserService {

to just:

export class UserService  {
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, yeah. Maybe this is the best answer although I can't seem to let go of my original intent. I don't see why I shouldn't be able to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.