3

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(?);
  }
}

2 Answers 2

4

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']);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@arthur-decker see this one
I didn't use a snapshot though but your logic gave me more ideas thanks
Works on my end. Been searching for almost a day. I was referencing the ActivatedRoute data and getting a null value.
3

First of all your route should be like this

 {
    path: 'hn/:id',
    component: HnDetailsComponent,
    resolve: {
      response: HnResolver
    },
}

Your resolver should like this one

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

  resolve(route: ActivatedRouteSnapshot, 
  state: RouterStateSnapshot): Observable<any> {
    return this.hnService.getTopPosts(route.data['id']);
  }
}

Note: is asummed that your route is something like http://localhost:4200/hn/4 where 4 is the ID of the hn that u want to see the details

in HnDetailsComponent details you can access to the hn resolved

export class HnDetailsComponent implements OnInit {

constructor(private route: ActivatedRoute) { }

  ngOnInit() {
   const myHnResolved = this.route.snapshot.data.response;
   console.log(myHnResolved)
  }
}

I hope this help u to solve your trouble.

2 Comments

I am not passing in an ID I am passing in an API url
Please, check the new answer Arthur and let me know if u this solve your trouble

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.