0

I am creating a Recipe object and saving it in my Django backend using CreateAPIView. After that Recipe is created I want to use its id value to create a Url redirect to another page where I can upload more information about the Recipe that was just created. I want to put the id value in the url because its easy to access it in the url, all i know how to do.

AddRecipeComponent

  submitrecipe(){
    this.recipeservice.addrecipe(this.newrecipe).pipe(
      map(res => this.response = res)
    )
    console.log(this.response) //THIS ALWAYS SHOW UNDEFINED IN THE CONSOLE
    this.router.navigate(['/recipeimage/'+this.response.id])
  }
}

recipe.service

  addrecipe(newrecipe):Observable<any>{
    return this.http.post(this.addrecipeUrl, newrecipe)
  }

views.py

class AddRecipe(generics.CreateAPIView):
    serializer_class = RecipeFullSerializer

serializer.py

class RecipeFullSerializer(serializers.ModelSerializer):
    class Meta:
        model = Recipe
        fields = ['name', 'id']

The problem is I cannot get the id parameter from the response in the RecipeComponent, I actually never see a value for response it is always 'undefined'. I know the observable is async, so thats probably why i always see it as undefined.

I think i need to wait for the asyn operation to complete? Or maybe there is a better way?

ratrace123
  • 976
  • 4
  • 12
  • 24

1 Answers1

0
  1. HTTP POST call is an asynchronous method.
  2. subscribe() is better that map() here. map is usually used to convert/map the response from one form to another.
  3. All the response specific logic should be within the subscription.
  4. It is also always good practice to handle the error when subscribing to HTTP calls.

Try the following

submitrecipe() {
  this.recipeservice.addrecipe(this.newrecipe).subscribe(
    res => {
      this.response = res;
      console.log(this.response);
      this.router.navigate(['/recipeimage/'+this.response.id]);
    },
    error => {
      // handle error
    }
  );
}
ruth
  • 29,535
  • 4
  • 30
  • 57