0
votes

Hi trying to find the best way to update component views, when a database has been modified,

At the moment I subscribe to an observable to get all records

   getBlogs(){
       return this._http.get(this.blogsURL+'blogs')
                  .map((result: Response ) => {
                  this.blogs = result['blogs'];
                    return this.blogs;
                   })
   }

And then

this.blogsService.getBlogs()
    .subscribe((res)=>{
      this.blogs = res;
      console.log(res)
    })

that's fine but when records update, the views in components don't. I can remedy this via a subject and when the getBlogs and update blogs functions are fired update it

this.populateList = new Subject<Blog[]>();
this.populateList.next(blogs)

Then subscribe, so I end up with something like this?

  this.blogsService.getBlogs()
    .subscribe((res)=>{
     // this.blogs = res;
      //console.log(res)
    })

  this.blogsService.populateList
        .subscribe((res)=>{
          this.blogs = res;
          console.log(res)
        })

but I'd like to get it all it to one subscription, maybe mergeMap switchMap? hope this makes sense

1

1 Answers

1
votes

If you simply want to asynchronously bind your Observable response coming from the service to your view, then don't subscribe to that observable at all in the component. Just call the service that returns the observable (and mapped) value. Then use the async pipe in view show the data dynamically. So each time another value is emitted or observed data changes, it will get automatically updated in view.

this.myBlogs = this.blogsService.getBlogs();

in template,

<div [innerHTML]="myBlogs | async"></div>

Hope you can make use of the idea to get to the end result. If this is not exactly what you are looking for, please do leave a comment.