1

I am very new to Angular(started today) and I'm simple trying to extend a tutorial from datafiles to the Django REST Framework and API calls. I cannot work out how to pass a variable to an http call to a Django Rest Framework api.

I have my app module / route specified thus:

import { BarDetailsComponent } from './bar-details/bar-details.component';
const routes: Routes = [
  ...
  { path: 'bar-details/:id', component: BarDetailsComponent },
  ...
]
@NgModule({
  declarations: [
    ...
    BarDetailsComponent,
    ...
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    HttpModule
  ],
  providers: [
    ...
    BarDetailsProvider,
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

BarDetailsComponent

import { Component, OnInit } from '@angular/core';
import { Bar } from '../bars/bar';
import { BarDetailsProvider } from './bar-details.provider';

@Component({
  selector: 'app-bar-details',
  templateUrl: './bar-details.component.html',
  styleUrls: ['./bar-details.component.scss']
})
export class BarDetailsComponent implements OnInit {

  bar: Bar;
  private selectedId : number;

  constructor(private barDetailsProvider: BarDetailsProvider) { }

  ngOnInit() {
    this.barDetailsProvider.getBarDetails().subscribe(bar => this.bar = bar);
  }

}

BarDetailsProvider

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Bar } from '../bars/bar';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';

@Injectable()
export class BarDetailsProvider {

  constructor(private http: Http) { }

  getBarDetails(): Observable<Bar> {
    return this.http.get(`${environment.baseUrl}/bar/1`).map(response => response.json() as Bar);
  }
}

Where I have return this.http.get(${environment.baseUrl}/bar/1).map(response => response.json() as Bar); above I want to replace 1 with the id which gets passed from the following html

<h1>Bars</h1>
<div *ngFor="let bar of bars">
  <a routerLink="/bar-details/{{bar.pk}}">
    <h2>Name: {{bar.name}}</h2>
  </a>
  <div>Address: {{bar.address}}</div>

  <hr>
</div>

How do I get the id I'm passing back into the get call?

1

3 Answers 3

3

Yea, you need to subscribe to your route param schanges into your component

constructor(private route: ActivatedRoute) {}

ngOnInit() {
     this.sub = this.route.params.subscribe(params => {
          const id = params['id'];

          this.barDetailsProvider.getBarDetails(id).subscribe(bar => this.bar = bar);
     });
}

and change your service accordingly

getBarDetails(id: string): Observable<Bar> {
    return this.http.get(`${environment.baseUrl}/bar/${id}`).map(response => response.json() as Bar);

}

Sign up to request clarification or add additional context in comments.

4 Comments

this gives me the error Property 'sub' does not exist on type 'BarDetailsComponent'.
)) you need to create it, this is just a variable. I thought it obvious
I'm really new to Angular. I've put it in as a variable sub: Subscription (I don't know if that is right) which generates js error "Cannot read property 'subscribe' of undefined"
you see this route in my code. this is ActivatedRoute class, and you need to add this into your constroctor. I'll edit my answer. @HenryM i'll explain all you need if you want.
0

1 way - when you change id in routing end update them (with subscribe)

BarDetailsComponent

import { ActivatedRoute } from '@angular/router';
....
constructor(private activeRoute: ActivatedRoute ..... {
   this.activeRoute.params.subscribe(element => {
     this.id = element['id']; //you get id
     this.barDetailsProvider.getBarDetails(this.id).subscribe(bar => this.bar = bar);
   })
   ....
}

2 way - without subscribe BarDetailsComponent

this.id = this.activeRoute.params['id']

in getBarDetails() function add id param

getBarDetails(id): Observable<Bar> {
    return this.http.get(`${environment.baseUrl}/bar/${id}`).map(response => response.json() as Bar);
}

Comments

0

asuming your path would be like this

{path: 'bar-details/:id', component: BarDetailsComponent}

export class PopDetailsComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private actRoute: ActivatedRoute){
this.subscription = this.actRoute.params.subscribe(
   (params: any) => {
   if (params.hasOwnProperty('id') && params['id'] != '') {
      this.fooId = params['id'];
 });
}
// dont forget to unsubscribe
 ngOnDestroy() {
  if(this.subscription) {
    this.subscription.unsubscribe();
  }
 }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.