malachi54 malachi54 - 6 months ago 446
JSON Question

Type 'Observable<any>' is not assignable to type 'JSON' in angular2 with rxjs5

i want to change all of my EventEmitter to Subjects since it is the recommended way to share variables and states instead of emitting an event.

but now i got a problem and just don't understand how to solve it. here is the sample code:

@Injectable()
export class TicketsService implements OnInit {
private _url = "http://127.0.0.1:3000/api/getAllTickets";
private _refreshTickets:Subject<JSON> = new Subject<JSON>();
public allTickets:JSON;

private _url_postNewTicket = "http://127.0.0.1:3000/api/postNewTicket";

constructor(private _http:AuthHttp) {
this.allTickets = this._refreshTickets
.mergeMap(() => this._http.get(this._url))
.map((res:Response) => res.json())
.cache();

}

refreshAllTickets() {
console.log("refresh all tickets..");
this._refreshTickets.next(null);
}
}


The compiler gives me the following error:


public/angular/app/tickets.service.ts(26,9): error TS2322: Type 'Observable' is not assignable to type 'JSON'.
[1] Property 'parse' is missing in type 'Observable'.


i guess i could write
allTickets:JSON
as
allTickets:any
but in the component i use ngFor to iterate - so i get the error from ngFor that it needs an array...

thanks in advance!

Answer

You can change allTickets to be of type: Observable<any> and then in your ngFor binding you can use the async pipe like so:

*ngFor="let ticket of allTickets | async"