How can I return an array as Observable in getTodoItems()?
It was Promise<Itodo[]>
and I used Promise.Resolve(TodoItems)
to return the array. But when I changed it to use Observable
instead of Promise
, I don't know how to return the data and couldn't make it work.
I tried Observable.of(TodoItems)
but it doesn't know the .of
function.
I keep getting these errors whatever I tried. Could you please help me with it? Thanks.
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/fromArray';
import { Itodo } from './todo'
const TodoItems: Itodo[] = [
{ todoId: 11, description: 'Mr. Nice' },
{ todoId: 12, description: 'Narco' },
{ todoId: 13, description: 'Bombasto' }
]
@Injectable()
export class TodoService {
constructor(private _http: Http) {
}
getTodoItems(): Observable<Itodo[]> {
return TodoItems.map((items => Itodo[]) => <Itodo[]>items);
}
addNewTodo(model: Itodo) {
TodoItems.push(model);
}
getTodoItem(id: number): Observable<Itodo> {
return this.getTodoItems()
.map((items: Itodo[]) => items.find(p => p.todoId === id)); }
}
Use the map() method to get an array of values from an array of objects in TypeScript, e.g. const ids = arr. map((obj) => obj.id) . The map method will return a new array containing only the values that were returned from the callback function. Copied!
There are various ways to create observables. You can create them from scratch by using Observable constructor (as we saw earlier). You can also create them by using RxJS create function or create them from other data structures such as an array or a promise by using the built-in function of RxJS …and much more.
An Observable is a collection of multiple input values that get processed using array methods such as map , reduce , filter , and so on. It comes in handy when handling asynchronous operations such as making HTTP requests, user-input events, and so on.
It's interesting to know that the RxJS project is using TypeScript actively and it helped to find bugs when the library was migrating from JavaScript. In the next section, you can find more articles to learn and keep improving your skills through RxJS.
Observable.of
is the correct method you are looking for. On my project, I'm using rxjs5-beta6 and import { Observable } from 'rxjs/Observable';
was enough to use the of
method. Depending on your project, you may need to explicitly import the of
method.
If all fails, you may try using Observable.from(TodoItems)
or even try creating your own observable which return your value.
e.g.
Observable.create((observer: Subscriber<any>) => {
observer.next(TodoItems);
observer.complete();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With