Search code examples
angulartypescriptnativescriptangularjs-serviceangular2-nativescript

Calling HTTP API via another Service


I am making a service call which internally calls http function via my component which runs perfectly fine and i do get a response. However when i am trying to make a http call via same service and via another method, it does not get processed and remain in pending state. I have tried to create a similar code above. Can anyone suggest on what can be the issue? As per my understanding, while making a call via a method in service, its not getting a subscriber. However i am not able to get the issue in below code.

Just to add, behavior which i am seeing is that http get call does not return the observable itself and .map function is not getting called when the call is done via same service

@Injectable()
export class MyService {
    // GET staff by location
    getData(): Observable<any> {
        // Set content headers
        let headers =     this.createRequestHeader(localStorage.getString("accessToken"));
        // Create a request option
        let options = new RequestOptions({ headers: headers });
    return this.http.get(url, options)
            .map(res => {
                return res.json()
            })
            .catch(this.handleErrors);
    
    }
    
    processQueue(): any { 
      while (!this.isQueueEmpty()){
      this.getData().subscribe((res) => {
                            this.popQueue();
                            console.log(res);
                        });
    }}
}

@Component({
    selector: "my-component",
    moduleId: module.id,
    templateUrl: "./my-component.component.html",
    styleUrls: ['./my-component.component.css']
})

export class MyComponent implements OnInit, OnDestroy {

  ngOnInit(private mySer:MyService): void {
    this.mySer.getData().subscribe(
                (res) => {
    console.log(res);
  }
}


Solution

  • There was no issue specific to a service vs. component. However issue was with the way the HTTP API was being called. After every API call, observable was being returned but the method was not getting time to execute. Queue was only popped when the subscription method is executed which never gets executed. Hence even though calling was right, all calls get added in PENDING.