Reputation: 91
I have a component that is listening to an Observable that returns information based off of a name provided in a string.
I would like to provide the name to the Observable by passing in a variable of the Activated Route parameter in the GET request. The problem is that when I use the variable within my GET request in the service, the URL is not detecting my variable and the request returns 'null'.
I suspect that my problem lies within my ngOnit in my component. The playerCode
in my getPlayer(playerCode)
.. I'm just not sure why..
If my playerCode is a string and I append that to my URL in the request, shouldn't that work?
In my component:
ngOnInit() {
const playerCode = this.route.snapshot.paramMap.get('player');
this.playerService.getPlayer(playerCode).pipe(
switchMap( player => {
let playerData = player["data"][0];
let anotherID = playerData.id;
return this.playerService.getSeasonStats(anotherID);
}))
.subscribe(id => this.player = id);
}
My Service that is using string variable in the URL:
getPlayer(player: string):Observable<Player[]> {
let getHeaders = new HttpHeaders({'Authorization':'API_Key', 'Accept': 'application/vnd.api+json'});
return this.http.get<Player[]>(`https://api.pubg.com/shards/steam/players?filter[playerNames]=`+ player, { observe:'body', responseType: 'json', headers: getHeaders, });
}
My app-routing component
const routes: Routes = [
{ path: 'players', component: CareerComponent },
{ path: 'players/:player', component: CareerComponent },
{ path: '**', redirectTo: 'players' }
Upvotes: 0
Views: 2203
Reputation: 134
Try to use
const routeparams = this.route.snapshot.queryParams
it will return an object of all the params and values and you can
then you can get the value of the player for your service with
routeparams['player']
Upvotes: 2
Reputation: 6529
The issue is with your routing. It will match the first route first so your dynamic variable will be ignored. Change your routing to this:
const routes: Routes = [
{ path: 'players', pathMatch: 'full', component: CareerComponent },
{ path: 'players/:player', component: CareerComponent },
{ path: '**', redirectTo: 'players' }
This will ensure that when your url is players/0203
it would match the second route and not the first one.
Upvotes: 1