简体   繁体   中英

How to `resolve` in subscription in RxJS for angular snapshot

I am rosolving a route using the resolver method like:

export const AppRoutes:Routes = [

    {path:"", component: HomeComponent, resolve:{ data:ResolveService } }

]

and my resolver do like this:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { ServerService } from '../../shared/service/server.service';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ResolveService implements Resolve<any>{

    googleApi:string = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";
    latitude:number;
    longitude:number;
    countryDetails:any;

    constructor(private http:HttpClient, private server:ServerService) { }

    async resolve(route:ActivatedRouteSnapshot){
        const response = await this.getCountryName(); 
        let countryPath  = this.countryDetails.countryShortName.toLowerCase() + '_' + this.countryDetails.countryShortName;
        let $url = `/assets/data/${countryPath}/${countryPath}.json`;
        return this.http.get($url).subscribe((data) => {
            console.log('data', data); //getting data here... how to put in snapdata
        });
    }

    getCountryName(){

        return new Promise((resolve, reject) => {

            if(navigator){
                navigator.geolocation.getCurrentPosition( pos => {

                    this.latitude = pos.coords.latitude;
                    this.longitude = pos.coords.longitude;
                    this.server.getCountry(this.latitude, this.longitude ).subscribe(values => {
                        this.countryDetails = values[0];
                        resolve(this.countryDetails);
                    })

                })
            }

        });

    }

}


// return this.http.get("./assets/home-load-resp.json").subscribe( 
//  res=> console.log(res), 
//  msg=> console.log(msg)
// );

But in my home I am getting as :

Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}

I am try to fetch the data like:

ngOnInit() {
        this.appData = this.snap.snapshot.data.data;

        console.log("this.appData", this.appData ); //gives above in console

    }

delete the subscription in your resolve function, try to return an observable from your resolver

async resolve(route:ActivatedRouteSnapshot){
    const response = await this.getCountryName(); 
    let countryPath  = this.countryDetails.countryShortName.toLowerCase() + '_' + this.countryDetails.countryShortName;
    let $url = `/assets/data/${countryPath}/${countryPath}.json`;
    return this.http.get($url);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM