1
if (form.Id_Product.id == undefined) {
    product.NameProduct = form.Id_Product;
    this.serviceproduct.postProduct(product).subscribe((result: Product) => {
        form.Id_Product = result;
        product = form.Id_Product;
        detailproduct.Id_Product = form.Id_Product.id;
    });

    // Here the value no longer comes out, as I do for
    // the value continues to persist
    console.log(detailproduct.Id_Product);
}

How can I make the value that my service returns to me persist in all my method, detailproduct.Id_Product = form.Id_Product.id, the value assigned to it only persists within that context, but if I call outside it comes out undefined.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Sergio Lopez
  • 59
  • 1
  • 18
  • One of the possible solutions - inject that value to your service. providers: [ UserService, { provide: APP_CONFIG, useValue: HERO_DI_CONFIG } ], – andrey.shedko Apr 20 '18 at 14:14
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jeremy Thille Apr 20 '18 at 15:16

2 Answers2

1

Well, this.serviceProduct.postProduct is surely an asynchronous operation that returns an Observable. When your console.log executes, the call to subscribe has not executed yet, so of course you don't get the value.

If you want to wait for that value to be available you must make sure all that code is executed from inside the call to subscribe.

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
0

create variable at the beginning of your component class and using this update your variable inside your function

for example -

test: string;

ngOnInit() {
   this.test = 'new value';
}

Another case for you that can be your subscribe gets the value after your console.log statement gets printed as it is async behaviour. So your value is initialised but not logged.

faizan baig
  • 1,283
  • 15
  • 21