Как использовать перехватчик в Angular 8? - PullRequest
0 голосов
/ 19 сентября 2019

У меня есть приложение Angular 8.И есть много вызовов API.Но

GET' | 'POST' | 'PUT' | 'DELETE',

настроены.вот так:

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

Но я хочу использовать библиотеку httpClient ANgular.

Потому что я хочу сделать это, например:

constructor(private http: HttpClient, private route: Router) { }


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

Но теперь метод getDossierEntry будет работать так:

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

и метод 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)) );
      } )
    );
  }

И потому что, если я так попробую это:

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

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

"SyntaxError: Unexpected end of input
    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)
    at callViewAction (http://localhost:4200/vendor.js:46248:21)"

Так что я должен изменить?

Спасибо

Это файл js:

import { Component, OnInit } from '@angular/core';
import { HealthAPIService } from '../../shared/health-api/health-api.service';
import { DossierEntry } from '../../interfaces/dossier/dossier-entry.interface';
import { DocumentCorrespondenceService } from 'app/shared/services/document-correspondence.service';

@Component({
  selector: 'app-dossier-physical',
  templateUrl: './dossier-physical.component.html'
})
export class DossierPhysicalComponent implements OnInit {
  entries: Array<DossierEntry> = [];
  single: DossierEntry;
  showSingle: boolean;
  dossiersLoaded = false;

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

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

  goToSingle(index: number) {
    this.single = this.entries[index];
    this.showSingle = true;
  }

  handleGoBack() {
    this.showSingle = false;
  }
}

...