Obed Lorisson
Obed Lorisson

Reputation: 449

How to return the value from the observable and assign it to a variable

i want to return a value from this method from an observable in order to use it in another function by assigning it to the viewcount variable. how do i properly return the value from the observable and assign it to a public variable for later use in this case.

public viewcount:any  

public getcount(id){
  let view = " ";
  this.backandService.getViews(id).subscribe(
    (data:any) =>{
      view = data["0"].views
      console.log(view)
    }
  );
  return view;
}

now in the other method i do

 public updateViews(id){
     let  view:any = this.viewcount;
       this.backandService.update('videos',id,
  {"viewcount":JSON.stringify(view)}).subscribe(
         data =>{
           console.log (data);
         }
       );
     }

but the value is never returned in order to use it in the updateView method and in the console log the updateView xhr requests show only a 404 not found for it also the request payload in the Headers show an empty bracket.

Upvotes: 1

Views: 1264

Answers (1)

Daryl
Daryl

Reputation: 18895

Because you are assigning the value to a module level variable, you can't make that variable a number, but it itself needs to be a promise.

public viewCount: Promise<number>;

public requestCount(id){
  this.viewCount = new Promise<number>((resolve,reject) => {
    this.backandService.getViews(id).subscribe(
      (data:any) =>{
        let view = data["0"].views;
        console.log(view);
        resolve(view);
    });
   });
}

public async updateViews(id): Promise<void>{
  let view = await this.viewcount;
  this.backandService.update('videos',id { 
    "viewcount":JSON.stringify(view)}).subscribe(data =>{
       console.log (data);
     });
  });
}

The non-async approach:

public updateViews(id): Promise<void>{
  return this.viewcount.then(view => ( 
    this.backandService.update('videos',id { 
      "viewcount":JSON.stringify(view)}).subscribe(data =>{
         console.log (data);
       });
    });
  })'
}

Upvotes: 1

Related Questions