0

I have some troubles using Observable. I did it as I did on another project where there's no problem, and here my Observable only returns simple objects instead of the one I declare in the response type of my function.

I have this in my service :

postLogin(login: string, credential: string): Observable<AuthToken> {
    let headers = new Headers({ "Content-Type": "application/json" })
    let jsonLogin = {"login": login, "password": credential}

    return this._apiEndpoint.postLogin(JSON.stringify(jsonLogin), headers)
                    .map(res => res.json())
}

Note that if I console.log my res.json(), I have all the fields I need for my AuthToken model.

If I console.log my returned variable in my component, I have it as Object with all the fields from the backend (if I remove or add some, they're there too). If I map manually all the fields as in here it sure works, but I used to have Observable doing it automatically.

Do you know what could be wrong ? Thanks !

Community
  • 1
  • 1
Guigui
  • 641
  • 4
  • 8
  • 23
  • This should work as intended. What problems are you having exactly? – Maximilian Riegler Aug 26 '16 at 13:10
  • The function returns simply what res.json() returns, and not the AuthToken model as I would like. AuthToken has "token", "firstName" and "lastName" parameters, and the API response has these 3 but also some others like "success":true for example, well I have them as well in the response I get in my component – Guigui Aug 26 '16 at 13:22
  • So what you want is only those 3 members without the `success` and so on? – Maximilian Riegler Aug 26 '16 at 13:26
  • The problem is, you have no types after transpiling to JavaScript, so the `Observable` doesn't know of what type it is. You're probably out of luck and have to map it yourself if you don't want the other variables in that object. – Maximilian Riegler Aug 26 '16 at 13:28
  • Yeah that's it, I want that my function returns an AuthToken type variable and not an Object. In this case it's not that much of a trouble, but if I make another class in which I put some functions in the model file, then I won't be able to use them – Guigui Aug 26 '16 at 13:29
  • 1
    Specifying a type on the Observable is merely for the sake of the compiler to attempt to prevent errors. It doesn't actually have any effect at runtime. You'll have to map it yourself. You can define a separate function that takes in a single parameter (the response from the Observable) then creates and returns an AuthToken object from the response. Pass the function itself to the `.map()` function, like so `.map(this.resonseToAuthToken)` and that will get you the end result you're looking for. – ABabin Aug 26 '16 at 15:43

0 Answers0