Reputation: 970
Im completely new to Angular 2. Im getting this error
Type 'Observable<{}>' is not assignable to type 'Observable<Token>'. Type {} is not assignable to type 'Token'. Property 'access_token' is missing in type {}.
Service
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Token } from './token';
import {Observable} from 'rxjs/Rx';
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class TokenService {
constructor(private http: Http) { }
getToken(): Observable<Token> {
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
var params = new URLSearchParams();
params.append('UserName', '[email protected]');
params.append('Password', 'Lasal@123');
params.append('grant_type', 'password');
return this.http.post('https://payd.azurewebsites.net//token', params.toString(), { headers })
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error));
}
}
}
I would like to know the reason behind this error and the solution for this. Thanks in advance!
Upvotes: 0
Views: 1285
Reputation: 41314
It's just Typescript letting you know you didn't assign types where you should.
getToken(): Observable<Token> {
return this.http.post(...)
.map((res: Response) => res.json())
}
This function expects to return an Observable
, which it does since http.post()
returns an observable. It also expects that this observable emits something of a type Token
, but it is returning any
:
(res: Response): any => res.json()
Because http.post()
doesn't actually know what you will get from server, it can't type that for you, you have to do it yourself:
(res: Response): Token => res.json()
or create new instance of Token
(if TS still complains):
(res: Response): Token => new Token(res.json())
Upvotes: 2