1

I am working on learning Angular and Typescript. Now, I want to do this:

  1. get user list from web api
public list$:Observable<{id:string,name:string,like:number}[]> = new Observable()

ngOnInit(): void {
   this.getData()
}

getData(){
   this.list$ = this.service.getUserList()
}
  1. render user list
<ul>
  <li *ngFor="let item of list$ | async">
    <input (ngModelChange) = "changeName($event,item.id)">
    ....
  </li>
</ul>
  1. change the user name by id
  async changeName(newName:string,id:string){
    const res = await this.service.changeName(newName,id).toPromise()
    if(res.success){
       // How to update this.list$ , without send a new request     
       // just like this:
       // this.userList = this.userList.map(i=>i.id === id ? { ...i, name:newName } : i)
    }
  }
  1. Is this something that can be done?

  2. If yes, is it something that SHOULD be done, or is there a better way to accomplish what I am trying to do?

    thinks!!!!

1
  • Subscribe it in the component, do your thing, render it. Unsubscribe in the onDestroy() method Commented Dec 9, 2021 at 9:26

2 Answers 2

1

Change your code to send item to changeName method and modify the item.name=newName inside changeName method after successful API update response. As we are passing the reference of the item we should see the name updated properly.

<ul>
  <li *ngFor="let item of list$ | async">
    <input (ngModelChange) = "changeName($event,item)">
    ....
  </li>
</ul>

And script

async changeName(newName:string,item:any){
    const res = await this.service.changeName(newName, item.id).toPromise()
    if(res.success){
       item.name=newName;
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

👍👍👍👍👍👍👍 thanks
@kkerwin Please upvote if you feel it helped you so that it will helps other and also motivates my work.
0

While the solution works. I don't think it's the recommended way to do.

The reason is, you are updating the data manually - set the name to signal/notify for the view to update.

With Observer/Observable - reactive programming, we want the view to update automatically whenever the data change.

The solution for this is to use Subject, where every time you change something, the Subject will push that change to its subscribers

2 Comments

[stackblitz.com/edit/… hello, When i use Subject,I can't get "the old data(the data from web api )", So i used BehaviorSubject , because i can use BehaviorSubject.value get the data. Is there anything wrong with me doing this? Can you give me an example? thanks!
True. In case you want "the old data", BehaviorSubject is needed. You learnt it quick, great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.