The plug connects with two watchers

I am using angular2fire. I ask and try to get all the tours from the city.

getAllTours(cityId) {
    return this.af.database.list(`/cities/${cityId}/tours`)
        .map((tours): any => {
            tours.map((tour: any) => {
                tour.tour  = this.af.database.object(`/tours/${tour.$key}/tours`)
            });
            return tours;
        })
}

If I console.log the tour object, I get an array of "FirebaseObjectObservable".

I need to go through the whole FirebaseObjectObservable to get the actual data.

I was wondering if I can go around all observables and get the output as an array with one subscription function.

This is the right approach.

I know that I can do an asynchronous channel in the entire array of observers, but I would like to get the data inside the controller and then do some processing before it is shown in the view, so the asynchronous channel is really not the best option for me.

+4
1

, forkJoin :

getAllTours (cityId) {
    return this.af.database
        .list(`/cities/${cityId}/tours`)
        .mergeMap((tours) => {

            // The array of tours is going to be mapped to an observable,
            // so mergeMap is used.

            return Observable.forkJoin(

                // Map the tours to the array of observables that are to
                // be joined. Note that forkJoin requires the observables
                // to complete, so first is used.

                tours.map((tour) => this.af.database
                    .object(`/tours/${tour.$key}/tours`)
                    .first()
                ),

                // Use forkJoin results selector to match up the result
                // values with the tours.

                (...values) => {
                    tours.forEach((tour, index) => { tour.tour = values[index]; });
                    return tours;
                }
            );
        });
}

forkJoin , .

, getAllTours, , , , . - /cities/${cityId}/tours , , /tours/${tour.$key}/tours , . , .

forkJoin , . ( , -, .)

, , , . , getAllTours:

observable = getAllTours(someCityId);
observable.map((tours) => {

    tours.forEach((tour) => {

        // With your function, tour.tour is an observable, so map
        // could be used to process the values.

        tour.tour = tour.tour.map((value) => {

            // Do some processing here with the value.
        })

        // And, if you are not interested in dynamic updates, you could
        // call first.

        .first();
    });
    return tours;
});

async .

+7

Source: https://habr.com/ru/post/1653605/


All Articles