1

I try to open my ng-bootstrap dialog but it's not working, i have no exception... How could to generate a generic service to handle 401 exception with a custom modal dialog ?

Service.ts

@Injectable()
export class SearchRequisitionService {
    apiURL: string;
    private modal: NgbModalRef;

    constructor(private http: Http, private modalService: NgbModal) {
        this.apiURL = 'requisition';
    }

    findRequisition(jsonSearchParams: string): Observable<Array<Reponse>> {
        let searchParams = JSON.stringify(jsonSearchParams);
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.post(this.apiURL + '/reponse', searchParams, {
            headers: headers
        }).map(this.extractData).catch(this.handleError);
    }

    findEtatsLists(): Observable<Array<EnumType>> {
        return this.http.get(this.apiURL + '/etatsAnalyse').map(this.extractData).catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    private handleError(error: Response | any) {
        // In a real world app, you might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {

            if (error.status === 401) {
                this.modalService.open(AuthModalContent);
            }
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

}

this.modalService is undefined but i declare everything in my Module.ts :

@NgModule({
    imports: [
        AnfiPortailSharedModule,
        FormsModule,
        NgbModule,
        NgxPaginationModule,
        RouterModule.forRoot(requiRoutes, {useHash: true})
    ],
    declarations: [
        SearchComponent,
        ResultsComponent,
        AuthModalContent,
        ClickOutsideDirective
    ],
    entryComponents: [AuthModalContent],
    exports: [],
    providers: [ConfigService, SearchRequisitionService, {
        provide: NgbDateParserFormatter,
        useFactory: customNgbDateParserFormatterFactory
    }],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AnfiPortailRequisitionModule {
}
Clement Martino
  • 463
  • 3
  • 17
  • This post gives me the solution => https://stackoverflow.com/questions/37988781/angular-2-injected-service-in-http-error-handler – Clement Martino May 31 '17 at 10:05

1 Answers1

0

http status may be a string, so you should use a simple "==" operator or cast status to int :

 if (parseInt(error.status, 10) === 401)
ip512
  • 128
  • 2
  • 9