Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve data from an api using angular route resolver

I am trying to use angular route resolver to load an endpoint before it displays but I can not find a way to go about it How do I pass the url of my API in my resolver as a parameter? For some unique reason I need to pass in an parameter so I can not pass the api in the service.

This is my service

@Injectable()
export class HnService {  
  constructor(private http: HttpClient) {}

  getTopPosts(endpoint) {
    return this.http.get(endpoint);
  }
}

This is my resolver file

@Injectable()
export class HnResolver implements Resolve<any> {
  constructor(private hnService: HnService) {}

  resolve() {
    return this.hnService.getTopPosts(?);
  }
}
like image 813
Arthur Decker Avatar asked Apr 13 '26 14:04

Arthur Decker


1 Answers

If you just want to pass data and access to this data in your resolver you can use the data property when you define the path.

First of all your route should be like this

 {
    path: 'hn/:id',
    component: HnDetailsComponent,
    resolve: {
      response: HnResolver
    },
    data:{
      apiURL: 'my/api/url'
    }
}

in the resolve

@Injectable()
export class HnResolver implements Resolve<any> {
 constructor(private hnService: HnService) {
}

  resolve(route: ActivatedRouteSnapshot, 
state: RouterStateSnapshot): Observable<any> {
    return this.hnService.getTopPosts(route.data['apiURL']);
  }
}
like image 126
YuryDG Avatar answered Apr 20 '26 14:04

YuryDG