1

I have a angular 8 application and want to call a Get api call.

But I get this error:

stack: "ReferenceError: result is not defined↵    at eval (eval at push../src/app/dossier/dossier-physical/dossier-physical.component.ts.DossierPhysicalComponent.ngOnInit 

This is the ts file:

export class DossierPhysicalComponent implements OnInit {
  entries: Array<DossierEntry> = [];
  single: DossierEntry;
  showSingle: boolean;
  dossiersLoaded = false;

  constructor(
    private healthAPIService: HealthAPIService,
    private documentCorrespondencService: DocumentCorrespondenceService
  ) {}

  ngOnInit() {
    this.healthAPIService.getDossierEntry('physical').subscribe(result => {
      console.log(result.values);
      this.entries = result;
      this.dossiersLoaded = true;
    });
  }
}

And this is the service:

 getDossierEntry( type: String = '' ): Observable<DossierEntry[]> {
    const entryType = type === '' ? 'all' : 'type/' + type;
    return this.http.get<DossierEntry[]>('/api/patient/{patientUUID}/DossierEntry/' + entryType );
  }

And this is the total error

HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical", ok: false, …}
error: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/patient/%7BpatientUUID%7D/DossierEntry/type/physical</pre>↵</body>↵</html>↵"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical"
__proto__: HttpResponseBase

So what I do wrong here?

Thank you

The problem Is that I try to refactoring the Get method. Because I have a service: health.api.service.

and there are customised api calls. Like this:


 get( route: string, responseType: RespType = 'json', fullResponse: boolean = false, params = null): Observable<any> {
    return this.invoke( 'GET', route, null, responseType, fullResponse, true, params);
  }

and the invoke method looks like this:

 invoke(
    method: 'GET' | 'POST' | 'PUT' | 'DELETE',
    route: string,
    body?: any,
    responseType: RespType = 'json', // PDF gets translated to array buffer and the application/pdf accept header
    fullResponse: boolean  = false,
    needsAuthenticatedUser = true,
    params: HttpParams = null
  ): Observable<any> {
    const user$ = this.authService.loginStatus()
                      .pipe( take( 1 ) );

    return user$.pipe(
      map( user => {
        let parsedRoute = route;
        if ( needsAuthenticatedUser ) {
          if ( !user ) {
            throw Error( 'Tried to call api that requires login without a user profile present' );
          } else {
            parsedRoute = parsedRoute.replace('{userId}', user.profile.sub);
            parsedRoute = parsedRoute.replace('{patientUUID}', user.profile.participant);
          }
        }
        return environment.ApiOrigin + parsedRoute;
      } ),
      switchMap( url => {
        const accessToken = this.authService.getAccessToken();

        const headers = {
          'Content-Type': 'application/json',
          'Accept'      : HealthAPIService._responseTypes[ responseType ].mime
        };

        if ( !!accessToken ) {
          headers[ 'Authorization' ] = `Bearer  ${accessToken}`;
        }

        const options = {
          body        : body,
          responseType: HealthAPIService._responseTypes[ responseType ].decode as
            | 'json'
            | 'text'
            | 'arraybuffer',
          headers     : new HttpHeaders( headers )
        };
        if ( fullResponse ) {
          options[ 'observe' ] = 'response';
        }
        if (params !== null) {
          options['params'] = params;
        }

        return this.http.request( method, url, options )
                   .pipe( catchError(err => this.handleError(err)) );
      } )
    );
  }

But I want to get rid of that customised Get method. And just want to call it with the HttpClient module of Angular.

This is the error handling:

private handleError( error: any ): Observable<any> {
    if ( error.status && error.status === 401 ) {
      console.error( 'Authorization failed, trying to login.' );
      this.authService.requestLogin();
    }
    console.dir( error );
    if ('error' in error) {
      // This is necessary to allow measurement-form-component
      // handleFormErrors to give correct feedback.
      return observableThrowError(error);
    }
    return observableThrowError( error.message || error );
  }

when I try thtat. I stiil get this error:

HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical", ok: false, …}
error: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/patient/%7BpatientUUID%7D/DossierEntry/type/physical</pre>↵</body>↵</html>↵"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical"
__proto__: HttpResponseBase
constructor: ƒ HttpErrorResponse(init)
__proto__: Object

So I have it now like this:

 ngOnInit() {
    this.healthAPIService.getDossierEntry('physical').subscribe((result: any)=> {
       console.log(result.values);
       this.entries = result;
       this.dossiersLoaded = true;
   });
 }

and this:

  getDossierEntry( type: String = '' ): Observable<DossierEntry[]> {
    const entryType = type === '' ? 'all' : 'type/' + type;
    return this.http.get<DossierEntry[]>('/api/patient/{patientUUID}/DossierEntry/' + entryType );
  }


then I will get this error:

core.js:7376 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical", ok: false, …}
error: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/patient/%7BpatientUUID%7D/DossierEntry/type/physical</pre>↵</body>↵</html>↵"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical"
__proto__: HttpResponseBase
stack: "ReferenceError: result is not defined↵    at eval (eval at push../src/app/dossier/dossier-physical/dossier-physical.component.ts.DossierPhysicalComponent.ngOnInit (http://localhost:4200/dossier-dossier-module-ngfactory.js:18184:14), <anonymous>:1:1)↵    at DossierPhysicalComponent.push../src/app/dossier/dossier-physical/dossier-physical.component.ts.DossierPhysicalComponent.ngOnInit (http://localhost:4200/dossier-dossier-module-ngfactory.js:18184:14)↵    at checkAndUpdateDirectiveInline (http://localhost:4200/vendor.js:37850:19)↵    at checkAndUpdateNodeInline (http://localhost:4200/vendor.js:46063:20)↵    at checkAndUpdateNode (http://localhost:4200/vendor.js:46025:16)↵    at debugCheckAndUpdateNode (http://localhost:4200/vendor.js:46659:38)↵    at debugCheckDirectivesFn (http://localhost:4200/vendor.js:46619:13)↵    at Object.updateDirectives (http://localhost:4200/dossier-dossier-module-ngfactory.js:18152:711)↵    at Object.debugUpdateDirectives [as updateDirectives] (http://localhost:4200/vendor.js:46611:21)↵    at checkAndUpdateView (http://localhost:4200/vendor.js:46007:14)"

and this is the HttpMaintenanceInterceptor:

@Injectable({
    providedIn: 'root'
  })
export class HttpMaintenanceInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService ) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${this.auth.getAccessToken()}`
        }
      });
      return next.handle(request);
    }
}


I have it now like this:


getDossierEntry( patientUUID: string, type: String = '' ): Observable<DossierEntry[]> {
  const entryType = type === '' ? 'all' : 'type/' + type;

  console.log(this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType));

  return this.http.get<DossierEntry[]>('/api/patient/${patientUUID}/DossierEntry/' + entryType);
}

and this:

 ngOnInit() {
    this.documentCorrespondencService.getDossierEntry('physical').subscribe((result: any)=> {
       console.log(result.values);
       this.entries = result;
       this.dossiersLoaded = true;
   });
 }

I get this output:

Observable {_isScalar: false, source: Observable, operator: MapOperator}
operator: MapOperator
project: ƒ (res)
thisArg: undefined
__proto__: Object
source: Observable {_isScalar: false, source: Observable, operator: FilterOperator}
_isScalar: false
__proto__: Object
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/all", ok: false, …}
error: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/patient/$%7BpatientUUID%7D/DossierEntry/all</pre>↵</body>↵</html>↵"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/all: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/all"
__proto__: HttpResponseBase

even if I do this:



getDossierEntry( patientUUID: string, type: String = '' ): Observable<DossierEntry[]> {
  patientUUID = '0d584905-fc20-4723-870a-0f0214419507';
  const entryType = type === '' ? 'all' : 'type/' + type;

  console.log(this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType ));

  console.log(patientUUID);
  return this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType );
}

doenst work

5
  • 2
    You're calling a URL that returns a 404 error. Probably your handling of the patientUUID in the URL is incorrect. Commented Sep 23, 2019 at 7:56
  • 1
    You seem not replacing patientUUID value when making the api call. Commented Sep 23, 2019 at 7:56
  • But why would the subscriber get that undefined, if it's an error? throwError("you won't see this message").subscribe(console.log) prints nothing. Is there an interceptor somewhere in the middle, eating HTTP error responses and emitting empty values? Commented Sep 23, 2019 at 8:25
  • Update post ok, will be nice Commented Sep 23, 2019 at 12:26
  • see post update Commented Sep 23, 2019 at 20:36

4 Answers 4

1

To achieve expected result, use below option of updating API url with patientUUID

Option 1:

 getDossierEntry( patientUUID: string, type: String = '' ): Observable<DossierEntry[]> {
    const entryType = type === '' ? 'all' : 'type/' + type;
    return this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType );
  }

Option 2: Other way of using patientUUID in URL

getDossierEntry( patientUUID: string, type: String = '' ): Observable<DossierEntry[]> {
        const entryType = type === '' ? 'all' : 'type/' + type;
        return this.http.get<DossierEntry[]>('/api/patient/${patientUUID}/DossierEntry/' + entryType);
  }

Issue : patientUUID value is not getting appended to URL at intended location and getting 404 not found as it turns out to be invalid

To fix this issue update API url as above with parameters - patientUUID and type and to debug add console before return to check the url as below

console.log(this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType)
Sign up to request clarification or add additional context in comments.

18 Comments

Thank you . I will check it tomorrow and wil let you now.
But can I sent you the files?
@mightycodeNewton, i dont think SO allows sending files, but you can create stackblitz to replicate your issue
But we can go to chat. But can you invite me for chat? Because I dont see the function here.
Naga, are you there? I am testing it now
|
0

As i see the response you are getting is 404, which means the URL is not found.

In your code,

you are not substituting the value of patientUUID that you can check in the URL

return this.http.get<DossierEntry[]>('/api/patient/{patientUUID}/DossierEntry/' + entryType

4 Comments

But what I have to change then?
Can you say What I do wrong? OR that I have to post more code? Would be nice
Hi I added the Interceptor. But what I have to change then? Thank you
But so How to emite the patientUUID then in the URL? Thank you
0

in developer mode you should add proxy.conf.json to forward to your server: for example:

{
  "/api": {
    "target": "http://localhost:1337",
    "secure": false
  }
}

3 Comments

I dont understand this. what is 1337?? I updated the post
it is just an example. my server is listening to on port 1337. If you call relative url(/api) you should redirect it to your server, if you call external with ip, you should set absolute url, since the relative calls back to server which runs angular.
Oke, but this is not the problem. I updated the post
0

Map result type to any or

ngOnInit() {
    this.healthAPIService.getDossierEntry('physical').subscribe((result:DossierEntry[])=> {
      console.log(result.values);
      this.entries = result;
      this.dossiersLoaded = true;
    });
  }

OR

  ngOnInit() {
    this.healthAPIService.getDossierEntry('physical').subscribe((result:any)=> {
       console.log(result.values);
       this.entries = result;
       this.dossiersLoaded = true;
   });
 }

9 Comments

Thank you for you help. But still get an error. Updated the post
could you please put result inside the parenthesis like ** (result:any)=>** and check once.
But has it nothing to do with the invoke method? Because I dont trigger that method ofcourse , when I am using the httpClient
atSantosh DO you have other suggestions?
I added the INterceptor
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.