在Prod构建出错之后,您提供了一个无效的对象,该对象应该在其中流。您可以提供一个Observable,Promise,Array或Iterable

时间:2019-05-07 09:12:31

标签: webpack rxjs observable angular7 behaviorsubject

我已经在我的应用中实现了ReplaySubject。在ng serveng build上运行正常。但是在使用ng build --prod创建构建后,然后开始显示错误为

  

您提供了一个无效的对象,该对象应在其中流。您可以   提供一个Observable,Promise,Array或Iterable。

Query Optimization with MySQL 8.0 and MariaDB 10.3

这是我的植入物

import { ReplaySubject, Observable, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { SsoService } from 'sso-sdk';
import { API, RG_SSO_HEADER, HEADER, SSO_DOCTOR_HEADER, COACHING_PLATFORM_HEADER, coachingPlatformApi } from "../../environments/environment";
import { catchError, retry } from 'rxjs/operators';
import { CookiesService } from './cookies.service';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  bearerKey = 'auth_bearer';
  userObj: { practitioner_id: string } = null;
  loggedInTokens: any;
  private bearerTokenValue;
  private bearerToken = new ReplaySubject<string>(1);

  /* Use this observable as an Authorization header for cross APIs */
  bearerTokenObservable = this.bearerToken.asObservable();

  constructor(
    private _ssoService: SsoService,
    private _http: HttpClient,
    private _cookies: CookiesService,
  ) { }

  public getPractitonerOrgId(providerId): Observable<any> {
    const id = providerId;
    const url = `${coachingPlatformApi.clientListProviders}/${id}`;
    const headers = new HttpHeaders(Object.assign({}, COACHING_PLATFORM_HEADER));
    return this._http.get(url, { headers: headers }).pipe(
      retry(3),
      catchError(this.handleServiceError)
    );
  }
  listenToTokensObservable() {
    this._ssoService.tokensObservable.subscribe(res => {
      if (!res) {
        // Tokens expired or User signed out
        this._cookies.deleteCookie(this.bearerKey);
        this._cookies.deleteCookie('CLINIC');
        location.href = '/';
      }
    });
  }

  /**
   * Fetch formatted tokens response for Cross APIs
   * @param tokens - Logged in response SSO tokens
   */
  private formatSSOTokens(tokens: any) {
    const loggedInTokens = Object.assign({}, tokens);

    /* Start: Formatting logged in tokens for crossexchange API */
    loggedInTokens.access_token = {
      token: tokens.access_token,
      expiration: this.formatExpiration(
        new Date(tokens.exp_access_token * 1000)
      )
    };

    loggedInTokens.id_token = {
      token: tokens.id_token,
      expiration: this.formatExpiration(new Date(tokens.exp_id_token * 1000))
    };

    loggedInTokens.refresh_token = {
      token: tokens.refresh_token
    };
    /* End: Formatting logged in tokens for crossexchange API */

    return loggedInTokens;
  }

  private formatExpiration(date: Date) {
    const dateString = date.toDateString(),
      splitDateString = dateString.split(' '),
      finalDateString = `${splitDateString[1]} ${splitDateString[2]}, ${
        splitDateString[3]
        } ${date.toLocaleTimeString()}`;

    // Final string example: Aug 23, 2018 12:17:28 PM
    return finalDateString;
  }

  /**
   * To receive tokens for exchange with cross APIs for Practitioner/Associate clinic setup and management
   * @param ssoTokens: Tokens received after login or already logged in SSO tokensObservable
   */
  fetchBearerTokensFromCrossex(ssoTokens) {
    this.loggedInTokens = this.formatSSOTokens(ssoTokens);
    // If practitioner/associate then fetch bearer tokens for communicating with cross APIs
    const headers = {
      ...RG_SSO_HEADER,
      ...HEADER,
      'X-Application': 'CROSS_DOCTOR'
    };

    if (!this.bearerTokenValue) {
      const bearerCookie = this._cookies.getCookie(this.bearerKey);
      if (!bearerCookie) {
        // If bearer token cookie doesn't exist
        this._http
          .post(API.rgSsoPoly, this.loggedInTokens, {
            headers: new HttpHeaders(Object.assign({}, RG_SSO_HEADER, HEADER))
          })
          .subscribe(
            res => {
              const auth = res && res['oauth'];
              if (auth) {
                const bearerToken = auth.token_type + ' ' + auth.access_token;
                this.bearerToken.next(bearerToken);
                this.bearerTokenValue = bearerToken;
                this._cookies.setCookie(this.bearerKey, bearerToken, 9);

                //this.authorizeToken(ssoTokens);

              } else {
                this.bearerToken.error('Authorization failed');
              }
            },
            () => {
              this.bearerToken.error('Authorization failed');
            }
          );
      } else {
        // If bearer token is saved in cookie
        const httpHeaders = new HttpHeaders(
          Object.assign({}, headers, {
            Authorization: bearerCookie
          })
        );
        this.pingCrossexToValidateBearerToken(
          API.crossxDocPing,
          httpHeaders
        ).subscribe(
          () => {
            // Success
            this.bearerToken.next(bearerCookie);
            this.bearerTokenValue = bearerCookie;
          },
          () => {
            // Error
            this.logout();
            this._cookies.deleteCookie(this.bearerKey);
            location.href = '/';
          }
        );
        // this.authorizeToken(ssoTokens);
      }
    }
  }

  authorizeToken(ssoTokens) {
    const body = {
      'access_token': {
        'expiration': this.formatExpiration(new Date(ssoTokens['exp_access_token'] * 1000)),
        'token': ssoTokens['access_token']
      },
      'user_profile': ssoTokens['user_profile'],
      'id_token': {
        'expiration': this.formatExpiration(new Date(ssoTokens['exp_access_token'] * 1000)),
        'issued_at': this.formatExpiration(new Date(ssoTokens['exp_access_token'] * 1000)),
        'token': ssoTokens['id_token']
      },
      'refresh_token': {
        'token': ssoTokens['refresh_token']
      }
    }
    return this._http.post(API.crossAuthorizeToken,
      { ...body },
      { headers: new HttpHeaders(Object.assign({}, SSO_DOCTOR_HEADER, { 'rg_user_type': 'practitioner' })) });
  }

  private pingCrossexToValidateBearerToken(pingRequestURL, httpHeaders: HttpHeaders) {
    return this._http.post(pingRequestURL, null, {
      headers: httpHeaders
    });
  }

  logout() {
    this._ssoService.signOut();
  }

  /**
   * Get bearer token to connect with cross backend
   */
  getBearerToken() {
    return this.bearerTokenValue;
  }

  /**
   * Get CROSS APIs related headers with Authorization
   */
  getCrossAPIHeaders() {
    return {
      ...HEADER,
      'X-Application': 'CROSS_DOCTOR'
    };
  }
  private handleServiceError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.message);
    } else {
      // The backend returned an unsuccessful response code.
      console.error(
        `Backend returned code ${error.status}, ` + `body was: ${error.error}`
      );
    }
    // return an observable with a user-facing error message
    return throwError('Something bad happened; please try again later.');
  }
}

版本

enter image description here

0 个答案:

没有答案