logo
down
shadow

Waiting for Subcription to finish in Angular


Waiting for Subcription to finish in Angular

Content Index :

Waiting for Subcription to finish in Angular
Tag : angular , By : Sascha Brossmann
Date : January 12 2021, 07:00 PM

wish help you to fix your issue There are multiple ways to fix the issue (i.e. resolver/guard) but I will propose a solution as per your current code. You should call ExpenseHandlerService.getExpenseData in the constructor of the ExpenseHandlerService. Also, change your expenseDataChanged type to BehaviorSubject. Having said that let's change the ExpenseHandlerService like this [See the code comments for the explaination]:
@Injectable(
  {
    providedIn: 'root'
  }
)
export class ExpenseHandlerService {

  //I think BehaviorSubject type should be Array<ExpenseDetails> instead of ExpenseDetails
  //As your question was not clear so I am assuming as Aray<ExpenseDetails>; If you want type as ExpenseDetails
  //then you will have to adjust the code accordinlgy
  //LETS KEEP THIS VARIABLE AS PRIVATE SO THAT NOONE FROM OUTSIDE CAN EMIT NEW VALUE
  //AND EXPOSE AN OBSERVABLE as public property [see below]
  private expenseDataChanged = new BehaviorSubject<Array<ExpenseDetails>>([]);

  //This should be subscribed by the consumers i.e. Components
  get expenseDataObs() {
     return this.expenseDataChanged.asObservable();
  }

  //NO NEED TO MAINTAIN THIS ARRAY AS BehaviorSubject.value will give us the last emitted array
  //private expenseData: Array<ExpenseDetails> = [];
  constructor( private http: HttpClient) {

    this.getExpenseData();

  }
/**
 * Fetched expense data and stored in the this.expenseData
 */
  getExpenseData() {
    console.log('Starting...');
    this.http.get("assets/model/data.json")
      .pipe(map(result => result)).subscribe(data => {

      //I AM NOT SURE IF YOU API CAN RETURN NULL OR NOT
      //STILL IF API RETURNS NULL THEN EMIT EMPTY ARRAY
      //ADJUST THIS CODE AS PER YOUR APP LOGIC
      if(!data) {
       data = [];
      }
      const arr = data as Array<ExpenseDetails>;

      //I AM NOT USING SLICE (with no argument will return same array) AS IT WAS NOT DOING ANYTHING;
      //IF YOU WANT TO USE THEN USE AS PER YOUR LOGIC
      this.expenseDataChanged.next(arr);
    });

  }

/**
 * Notifies other components of any change in the data
 *
 * @param data
 */
  addExpenseData(data: ExpenseDetails) {

    //Get the last emited array from behaviorsubject
    const lastEmittedArr = this.expenseDataChanged.value;

    //push the data in to newArray
    //NOTICE I AM CREATING NEW ARRAY - This is to make sure that array is rendered; again it is NOT mandatory
    //but it depends on kind of changedetection stretegy is used.
    const newArrayToEmit = [...lastEmittedArr, data];
    this.expenseDataChanged.next(newArrayToEmit);
  }
}
ngOnInit() {
    this.expenseHandlerService.expenseDataObs
        .pipe(

          //As soon as you subscribe the initial value could be an null because the Behavior subject was initialized with null
          //THIS IS BECAUSE OF THE NATURE OF BehaviorSubject; It may happen because by the time you subscribe
          //response of HTTP API might not have recieved; but as soon as it is received
          //Using the filter will ensure to avoid null in callback
          filter(arr => !!arr)
        )
        .subscribe((res) => {

      //Process the array recieved;
      this.receiveExpenseData(res);
    });
  }

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Angular - $q not working as intended / help waiting for $http to finish


Tag : javascript , By : Nic Doye
Date : March 29 2020, 07:55 AM
it should still fix some issue I think you might be able to use some thing simular to this to get it to work:
d2jive.factory('spotifyFactory', function($http){
    var spotifyFactory = {

      var spotifyUrl = "http://ws.spotify.com/search/1/track.json?q=";

      getTracks: function(artstName){
         var promise = $http.get(spotifyUrl + encodeURIComponent(artistName))
                       .then(function (result){
           //this is where you modifiy the results
           var tracks = result.tracks.slice(0,9);
           for (var track in tracks){
              grabbedTrack = tracks[track]
                             .href.slice(14,tracks[track].href.length);
              trackArray.push(grabbedTrack);
           }  
           tracks.spotifyTracks = trackArray;  
           console.log(tracks.spotifyTracks);
           return tracks
         });
         return promise;
     });
     return spotifyFactory
});
spotifyFactory.getTracks(someArtist).then(function(d) {
   $scope.data = d;
});

Angular 2 - How can I block GUI rendering while waiting on http request to finish


Tag : javascript , By : CookingCoder
Date : March 29 2020, 07:55 AM
To fix the issue you can do It's possible to wait rendering the GUI/components and show it when the task has finished.
<div *ngIf="data">
  {{content}}
</div>
http.get(...).subscribe(val => this.data = val);

Angular 2 why aren't my 4 api calls waiting for the previous call to finish before executing?


Tag : angular , By : Stuka
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Theres quite a few issues with your code which might be contributing. Firstly your save1/save2/save3 methods should just return the observable from your API which you will be able to subscribe to.
Secondly you're using the int type which doesn't exist in Typescript. Use number.
private save1(saveObject: any): Observable<number> {
  return this.api.save1(saveObject);
}
// or
private save1(saveObject: any): Observable<number> {
  return this.api.save1(saveObject).map(response => 1).catch(response => 0)
}
save() {
  this.save1(saveObject1)
    .flatMap(response1 => this.save2(saveObject2))
    .flatMap(response2 => {
      if (response2 === 0) {
        // handle error
      }
      return this.save3(saveObject3);
    })
    .flatMap(() => this.save4(saveObject4))
    .subscribe(response4 => {
      // do redirect
    });
  }

Failed: Timed out waiting for asynchronous Angular tasks to finish after 11 seconds


Tag : javascript , By : orneka
Date : March 29 2020, 07:55 AM

angular waiting for a method to finish or a variable to be initialized


Tag : javascript , By : nobodyzzz
Date : March 29 2020, 07:55 AM
will help you I have a service used as a local data store to share data across the app. This service makes a few rest calls in the beginning to initialize some data. It look like this: , remove initializeData() from constructor and do something like this:
public async initializeData()
{
   this.optyList = await this.dataService.getObjectData('opportunities').toPromise();
   this.leadList = await this.dataService.getObjectData('leads').toPromise();
}


async ngOnInit() 
{
     await initializeData();

     for(let lead of this.dataStore.leadList){
         if(lead.accepted == false)
         this.newLeadsList.push(lead)
     }  
}  
Related Posts Related QUESTIONS :
  • Error: Can't resolve all parameters for setupPlatform: (?, [object Object], [object Object])
  • Differences between ng build and ng build --watch
  • Does an angular component ever destroy when it is subscribed to router change event once?
  • How do I get the JSON response from httpModule.get?
  • Ngx-logger implementation in angular 8
  • font size increase decrease by button using angular 7
  • Are selectors and module declarations mandatory for components?
  • Why angular is adding '#' in each route?
  • how to block the subsequent clicks in angular?
  • Ionic Angular TypeError: architect_1.createBuilder is not a function
  • Angular app doesn't work on Firefox after updating it to Version 8
  • Angular: Formatting numbers percentage
  • Matrix in FormGroup [Angular 2+]
  • "export 'DOCUMENT' was not found in '@angular/platform-browser'
  • angular autocomplete material
  • Prevent click event from triggering other click elements undernethe the front element
  • How to know when an image has been fully loaded in angular?
  • How to read config file to set API URL inside an Angular App packaged as a WAR and deployed on IBM Liberty
  • npm ERR! Unexpected end of JSON input while parsing near
  • override custom scss variable inside another angular-cli(7) (library) project
  • Angular-7 How to navigate to certain section of the single page website
  • how to disable an input field from a group of input fields in Angular
  • How to unit test selection of a mat-autocomplete option?
  • angular 8 form reset with value not working correctly
  • ng: error in production with Cb(...).firestore is not a function
  • Property 'result' does not exist on type 'EventTarget'
  • Cannot read property 'subscribe' of undefined on Ionic 4 , Angular 8
  • Repository is not clean. Please commit or stash any changes before updating In Angular 8
  • @angular-devkit/core module not found after angular-cli global fresh install
  • Lazy module loading error after updating to Angular 8
  • Using mat-tab-group focusChange event, How to stop user navigating to other tab
  • Best practice class member initialization
  • Angular 8 : TypeError: Found non-callable @@iterator
  • ng build --prod non-exported function
  • (Ionic4) How to dynamically go to previous page?
  • Angular 8.0.1 platform.es5.js:102 Uncaught TypeError: Object(...) is not a function
  • Zsh : command not found : ng on new Mac OS Catalina
  • Ag grid: How to add a row with sorting order
  • Failed to construct 'Worker': Module scripts are not supported on DedicatedWorker yet in Angular 8
  • How to write a function which will be return : Observable <ModelTemp>
  • cannot compile Ivy Rendering Engine in Angular 8
  • What is best way to apply ngif directive to <li> element?
  • Angular 7: Trigger valuechanges on addControl, if value's present
  • Function inside a ts file
  • Angular - Are admin files downloadable?
  • node_modules/@angular/cdk/table"' has no exported member 'CdkTextColumn'
  • node_modules/rxjs/Subject"' has no exported member 'Subject'
  • Angular - how to http service subscribe without response
  • how to test all my Service are injected into component
  • After upgrading to Angular8, AppEngine is serving scripts with the incorrect mime-type
  • Angular 6 - Cannot read property 'outlets' of null
  • Setting up background img with angular 7
  • Make BehaviorSubject persist across browser tabs? (@HostListener?)
  • Angular 7 : How to deploy Angular "Build" folder along with ASP.Net Web Api in Visual Studio 2017
  • How return name of image from FormControl in ReactivForms
  • Angular 7 HTTP Post 500 Internal Server Error
  • Ionic show data which is equal to the value
  • Angular directive inputs over component from another module cause an error
  • ValidationError: Progress Plugin Invalid Options
  • Angular mat-table : - Sort icon missing on custom sort
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com