-1

I am using a Subject to add edit functionality to a basic phonebook app. The changes that I make to component class variables inside of the subscribe callback are not reflected out of it or in the template.

I have tried the solutions listed in the answers to the following question: Angular 2 View will not update after variable change in subscribe

in service.ts:

startedEditing= new Subject<number>();

in details.component.ts(where the data is passed on fu):

onEdit(){
    this.contactsService.startedEditing.next(this.id);
  }

in edit-component.ts(in ngOnInit):

this.subscription=this.contactsService.startedEditing.subscribe(
      (index:number)=>{
        this.editMode=true; 
        this.editedItemIndex=index;
        this.editItem=this.contactsService.getContact(this.editedItemIndex);         
          this.editForm.setValue({
            address:this.editItem.address,
            name: this.editItem.name,
            phone:this.editItem.phone,
            profession:this.editItem.profession
          });
          console.log("in subscribe: "+this.editedItemIndex);

      }
    );
    console.log("out of it :" + this.editedItemIndex);
  }

output on the console:

in subscribe: 0
out of it : undefined

expected result:

in subscribe: 0
out of it :0

2 Answers2

0

The console.log("out of it :") will run only when your component is initialized, and at this moment this.editedItemIndex is undefined because startedEditing didn't change so the line this.editedItemIndex=index has not been triggered.

It's asynchronous ! If you do a startedEditing.subscribe() it's because you are waiting something (Ex: a value). If you try to get the value outside the subscribe, it will not wait for the value and will show undefined.

And if you try your code, the real output should be :

out of it : undefined
in subcribe : 0
Martin Paucot
  • 1,191
  • 14
  • 30
0

It is normal that this.editedItemIndex is undefined in console.log("out of it :" + this.editedItemIndex); The code above this part is asynchronous so when console.log("out of it :" + this.editedItemIndex); is run, the code inside the subscribe is not yet executed and this.editedItemIndex is not yet initialized. Now the ngOnInit is the first method that is called in your component so in the other methods or in the template, this.editedItemIndex should be already initialized and not undefined. may be you can share your html code or the other places where it is undefined so the answer can be more precise.

Ichraf
  • 345
  • 1
  • 7