Johnczek
Johnczek

Reputation: 657

Service wont autoinject in catch api angular block

I have a small problem here. I have an api service which loads data from API.

const API_URL = environment.apiUrl;

@Injectable()
export class ApiService {
    private headers = new HttpHeaders({
        'Content-type': 'application/json'
    });

  constructor(
      private http: HttpClient,
      private alertService: AlertService
  ) { }

  public getHotelById(hotelId: number) {
      return this.http
          .get(API_URL + '/hotel/' + hotelId)
          .map((response) => {
              return response;
          }).catch(this.handleError)
  }

  public getHotelsPreview(): Observable<any> {
      return this.http
          .get(API_URL + '/hotels/preview')
          .map( (response) => {
              console.log(this.alertService);
              return response;
          })
  }


  private handleResponse(response:any) {
      console.log(response.headers);
  }

  private handleError (response: Response | any) {
      const error = response.error;

      if(error.messages != null && error.messages.length > 0) {
          const errorMessages = error.messages;

          for(let message of errorMessages) {
              let alert = new Alert();
              alert.message = message.messageContent;

              switch (message.messageType) {
                  case "info":
                      alert.type = AlertType.Info;
                      break;
                  case "warning":
                      alert.type = AlertType.Warning;
                      break;
                  case "success":
                      alert.type = AlertType.Success;
                      break;
                  default:
                      alert.type = AlertType.Error
              }
              this.alertService.constructAlert(alert);
          }
      }

      return Observable.throw(error);
  }

}

When the problem occures, I catch the response using catch (as u can see on the gethotelbyid method) and handle it in handleerror method. Its basically just load of messages and push them into alert service (alert service just show all bootstrap alerts on the page, but it does not matter here).

The problem is the injection of alert service. When I try to console log alert service inside the handleError method, its undefined. When I try to console log the alert service somewhere else (for example in getHotelsPreview() method) it just shows the alertservice object and everything is okay. I can call its methods etc.

Why is this happening? I need to use that service to send the data into it and I cant. For some reason. Do I need to inject it in diferent way cause its in the catch block? I really dont understand. It should be injected when the class is constructed (so a lot of time before the actual response from the API came back).

To complete information abut project, I have all services included in app.module.ts this way

  providers: [
      AlertService,
      ApiService,
  ]

Upvotes: 0

Views: 32

Answers (1)

Antoniossss
Antoniossss

Reputation: 32535

You are loosing this context. Do

    }).catch(this.handleError.bind(this)

or arrow function

Upvotes: 1

Related Questions