вызов API в Angular 8, результат не определен - PullRequest
0 голосов
/ 23 сентября 2019

У меня есть приложение angular 8 и я хочу вызвать вызов Get API.

Но я получаю эту ошибку:

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

Это файл ts:

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;
    });
  }
}

А это сервис:

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

А это общая ошибка

<code>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
↵ ↵ ↵ "заголовки: HttpHeaders {normalizedNames: Map (0), lazyUpdate: null, lazyInit: ƒ} сообщение: «Http error response для 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

Так что же я здесь не так делаю?

Спасибо

Проблема в том, что я пытаюсь реорганизовать метод Get.Потому что у меня есть сервис: health.api.service.

и есть настроенные вызовы API.Вот так:


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

и метод invoke выглядит так:

 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)) );
      } )
    );
  }

Но я хочу избавиться от этого настроенного метода Get.И просто хочу вызвать его с помощью модуля HttpClient Angular.

Это обработка ошибок:

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 );
  }

, когда я пытаюсь thtat.Я получаю эту ошибку:

<code>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
↵ ↵ ↵ "заголовки: HttpHeaders {normalizedNames: Map (0), lazyUpdate: null, lazyInit: message} сообщение:" Http ошибка ответа для 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: ƒ HttpErrorResponse (init) __proto__: Объект

Так что теперь у меня это так:

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

и вот это:

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


тогда я получу эту ошибку:

<code>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
↵ ↵ He «Заголовки: HttpHeaders {normalizedNames: Map (0), lazyUpdate: null, lazyInit: ƒ} сообщение:« Http error response для http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical: 404 Not Found »name:« HttpErrorResponse »ok: ложный статус: 404 statusText:« NotНайден "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)"

, и это 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);
    }
}


У меня теперь это так:


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);
}

и это:

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

Я получаю этот вывод:

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
<code>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
↵ ↵ ↵ "онaders: HttpHeaders {normalizedNames: Map (0), lazyUpdate: null, lazyInit: ƒ} сообщение: «Http-ответ об ошибке для http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/all: 404 Not Found» name: «HttpErrorResponse» ok: ложный статус: 404 statusText: «Not Found»url: "http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/all" __proto__: HttpResponseBase

, даже если я сделаю это:



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

Ответы [ 4 ]

1 голос
/ 23 сентября 2019

Для достижения ожидаемого результата используйте нижеприведенную опцию обновления URL API с помощью patientUUID

Опция 1:

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

Опция 2: Другой способ использования patientUUID в URL-адресе

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

Проблема : patientUUID Значение не добавляется к URL-адресу в заданном месте и не получает 404, как оказалосьбыть недействительным

Чтобы исправить эту проблему, обновите URL API, как указано выше, с параметрами - PatientUUID и введите и отладьте консоль add перед возвратом, чтобы проверить URL, как показано ниже

console.log(this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType)
0 голосов
/ 23 сентября 2019

в режиме разработчика вы должны добавить proxy.conf.json для пересылки на ваш сервер: например:

{
  "/api": {
    "target": "http://localhost:1337",
    "secure": false
  }
}
0 голосов
/ 23 сентября 2019

Сопоставить тип результата с любым или

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

ИЛИ

  ngOnInit() {
    this.healthAPIService.getDossierEntry('physical').subscribe((result:any)=> {
       console.log(result.values);
       this.entries = result;
       this.dossiersLoaded = true;
   });
 }
0 голосов
/ 23 сентября 2019

Как я вижу, вы получаете ответ 404, что означает, что URL не найден.

В вашем коде

вы не подставляете значение patientUUID, которое вы можете проверить по URL

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