@angular/common/http#HttpHeaders TypeScript Examples

The following examples show how to use @angular/common/http#HttpHeaders. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: mediaObjects.service.ts    From Smersh with MIT License 6 votes vote down vote up
insert(data: FormData): Promise<AbstractModelApplication> {
    return this.http
      .post(`${this.getUrl()}`, data, {
        headers: new HttpHeaders({
          Authorization: `Bearer ${new Token().get()}`,
        }),
      })
      .toPromise()
      .then((result: any) => this.serializer.serialize(result));
  }
Example #2
Source File: error-handler.service.ts    From worktez with MIT License 6 votes vote down vote up
loadXML() {
    this.http.get('/assets/errorCodes.xml', {
      headers: new HttpHeaders()
        .set('Content-Type', 'text/xml')
        .append('Access-Control-Allow-Methods', 'GET')
        .append('Access-Control-Allow-Origin', '*')
        .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method"),
      responseType: 'text'
    })
      .subscribe((data) => {
        this.parseXML(data).then((data) => {
          this.xmlItems = data;
        });
      });
  }
Example #3
Source File: choice.ts    From json-schema-form with Apache License 2.0 6 votes vote down vote up
/**
     * handle GET / POST
     */
    getChoices(url: string, args: any, verb: string): Observable<any> {
        if (verb === 'GET') {
            return this.http.get<any[]>(url, args);
        } else {
            return this.http.post<any[]>(url, args, {
                headers: new HttpHeaders({
                    'Content-Type': 'application/json',
                })
            });
        }
    }
Example #4
Source File: proposal.service.ts    From Elastos.Essentials.App with MIT License 6 votes vote down vote up
/**
     * Returns a JWT result to a given callback url, as a response to a CR command/action.
     * Ex: scan "createsuggestion" qr code -> return the response to the callback.
     */
    public sendProposalCommandResponseToCallbackURL(callbackUrl: string, jwtToken: string): Promise<void> {
        return new Promise((resolve, reject) => {
            Logger.log('crproposal', "Calling callback url: " + callbackUrl);

            let headers = new HttpHeaders({
                'Content-Type': 'application/json'
            });

            this.http.post<any>(callbackUrl, {
                jwt: jwtToken
            }, { headers: headers }).subscribe((res) => {
                Logger.log('crproposal', "Callback url response success", res);
                resolve();
            }, (err) => {
                Logger.error('crproposal', err);

                if (err.error && err.error.message)
                    reject(err.error.message); // Improved message
                else
                    reject(err); // Raw error
            });
        });
    }
Example #5
Source File: git.service.ts    From img-labeler with MIT License 6 votes vote down vote up
public commitFile(user: string, message: string, content: string, sha: string, branch: string, imageName: string) {
    this.setHeaders();
    const body = {
      "message": message,
      "sha": sha,
      "branch": branch,
      "content": content
    };
    let header = new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': localStorage.getItem('gitToken')
    });
    let url = `https://api.github.com/repos/${user}/comma10k/contents/masks/${imageName}`;
    if(imageName.indexOf('_') === 5){
      url = `https://api.github.com/repos/${user}/comma10k/contents/masks2/${imageName}`;
    }
    return this.http.put(url, body, {headers: header});
  }
Example #6
Source File: basic-error-controller.service.ts    From mycoradar with MIT License 6 votes vote down vote up
/**
   * error
   * @return OK
   */
  errorUsingGETResponse(): __Observable<__StrictHttpResponse<{[key: string]: {}}>> {
    let __params = this.newParams();
    let __headers = new HttpHeaders();
    let __body: any = null;
    let req = new HttpRequest<any>(
      'GET',
      this.rootUrl + `/error`,
      __body,
      {
        headers: __headers,
        params: __params,
        responseType: 'json'
      });

    return this.http.request<any>(req).pipe(
      __filter(_r => _r instanceof HttpResponse),
      __map((_r) => {
        return _r as __StrictHttpResponse<{[key: string]: {}}>;
      })
    );
  }
Example #7
Source File: base-http.service.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
downZip(path: string, param?: NzSafeAny, config?: MyHttpConfig): Observable<NzSafeAny> {
    config = config || {needSuccessInfo: false};
    let reqPath = this.uri + path;
    if (config.otherUrl) {
      reqPath = path;
    }
    return this.http.post(reqPath, param, {
      responseType: 'blob',
      headers: new HttpHeaders().append('Content-Type', 'application/json')
    });
  }
Example #8
Source File: http-req.interceptor.ts    From open-genes-frontend with Mozilla Public License 2.0 6 votes vote down vote up
intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    let headers = new HttpHeaders();
    headers = headers
      .append('Accept', 'application/json')
      .append('Content-Type', 'application/json');


    if (req.url.includes('/api/') && !req.url.includes('https')) {
      const request = req.clone({
        headers,
        url: environment.apiUrl + req.url,
      });
      return next.handle(request);
    }

    return next.handle(req);
  }
Example #9
Source File: http.service.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
private _buildRequestOptions(
    method: string,
    url: string,
    body: any,
    tenant: string,
    username: string,
    accessToken: string,
    options?: any,
  ): any {
    options = options || {};

    let headers: HttpHeaders = new HttpHeaders({
      'X-Tenant-Identifier': tenant,
      'User': username,
      'Authorization': accessToken,
    });
    if (!(body instanceof FormData)) {
      headers = headers.set('Accept', 'application/json').set('Content-Type', 'application/json');
    }

    const optionsObject = {
      body: body,
      headers: headers,
      ...options,
    };
    const requestOptions: any = {
      method: method,
      url: url,
      options: optionsObject,
    };
    return requestOptions;
  }
Example #10
Source File: practise.component.ts    From ledge with Mozilla Public License 2.0 6 votes vote down vote up
async getCase(source: string) {
    this.src = this.buildSrc(source);
    this.currentSource = source;

    const headers = new HttpHeaders().set(
      'Content-Type',
      'text/plain; charset=utf-8'
    );
    this.http
      .get(this.src, { headers, responseType: 'text' })
      .subscribe((response) => {
        this.content = response;
      });
  }
Example #11
Source File: app.component.ts    From blog2020 with MIT License 6 votes vote down vote up
submit(formValues: { firstname: string, lastname: string, age: number, gender: string }): void {

    const encodedUserRequest = UserRequest.encode({
      firstname: formValues.firstname,
      lastname: formValues.lastname,
      age: formValues.age,
      gender: (formValues.gender === 'MALE') ? UserRequest.Gender.MALE : UserRequest.Gender.FEMALE
    }).finish();

    const offset = encodedUserRequest.byteOffset;
    const length = encodedUserRequest.byteLength;
    const userRequestArrayBuffer = encodedUserRequest.buffer.slice(offset, offset + length);

    const headers = new HttpHeaders({
      Accept: 'application/x-protobuf',
      'Content-Type': 'application/x-protobuf'
    });

    this.httpClient.post(`${environment.SERVER_URL}/register-user`, userRequestArrayBuffer, {headers, responseType: 'arraybuffer'})
      .pipe(
        map(response => this.parseProtobuf(response)),
        catchError(this.handleError)
      ).subscribe(this.handleResponse);
  }
Example #12
Source File: authentication.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Add the current authentication information to the passed `HttpHeaders` and `HttpParams`.
     * Currently, this adds the `sinequa-csrf-token` value to the HTTP headers. Called from
     * {@link HttpInterceptor}
     *
     * @param config HttpHeaders and HttpParams to be updated
     *
     * @returns new configuration
     */
    addAuthentication(config: {headers: HttpHeaders, params: HttpParams}): {headers: HttpHeaders, params: HttpParams} {
        this.doAuthentication();
        if (this.authentication) {
            if (this.authentication.headers) {
                for (const header in this.authentication.headers) {
                    if (this.authentication.headers.hasOwnProperty(header)) {
                        config.headers = config.headers.set(header, this.authentication.headers[header]);
                    }
                }
            }
            if (this.authentication.params) {
                for (const param in this.authentication.params) {
                    if (this.authentication.params.hasOwnProperty(param)) {
                        config.params = config.params.set(param, this.authentication.params[param]);
                    }
                }
            }
        }
        return config;
    }
Example #13
Source File: chat.service.ts    From loopback4-microservice-catalog with MIT License 6 votes vote down vote up
get(token: string, channelId: string) {
    const authHeader = new HttpHeaders({Authorization: `Bearer ${token}`});
    return this.http.get<Chat[]>(baseUrl, {
      headers: authHeader,
      params: {
        ChannelID: channelId,
      },
    });
  }
Example #14
Source File: customers-group.service.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
   * Handles 'deleteCustomer' function. Calls put method with specific api address
   * along its param.
   * @param params from model
   */
  // deleteCustomersGroup(params: any): Observable<any> {
  //     console.log(params.id, 'ser');

  //     return this.http.delete<any>(
  //       this.url + '/customer-group/delete-customer-group/' + params.id, params
  //     );
  //   }

  deleteCustomersGroup(value: any) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      withCredentials: false,
      body: { groupId: value.groupId }
    };

    return this.http.delete(
      this.url + '/customer-group/delete-customer-group/' + value.groupId,
      httpOptions
    );
  }
Example #15
Source File: rest-api.ts    From StraxUI with MIT License 6 votes vote down vote up
protected getHttpOptions(
    accept: string,
    contentType: string,
    httpParams?: HttpParams,
  ): {
      headers?: HttpHeaders | {
        [header: string]: string | string[];
      };
      params?: HttpParams | {
        [param: string]: string | string[];
      };
    } {
    return {
      headers: new HttpHeaders({
        'Accept': accept,
        'Content-Type': contentType,

      }),
      params: httpParams
    };
  }
Example #16
Source File: position.page.ts    From casual-chess with GNU General Public License v3.0 6 votes vote down vote up
sendNotification() {
    if (this.playerType == 'w' && this.game.hasOwnProperty('bpnotif') && !this.game.bpnotif)
      return;
    if (this.playerType == 'b' && this.game.hasOwnProperty('wpnotif') && !this.game.wpnotif)
      return;
    if (this.opponent && this.opponent.pushSubscription) {
      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json; charset=utf-8',
          'Accept': '"application/json; charset=utf-8',
          'Access-Control-Allow-Origin': '*'
        })
      };
      const formData = {
        jsonSub: this.opponent.pushSubscription,
        notificationTitle: 'Casual Chess',
        notificationBody: this.texts['position.move-notification-text']
      };
      this.http.post<any>(environment.sendNotificationUrl, formData, httpOptions)
        .subscribe(
          data => { },
          err => { },
          () => { }
        );
    }
  }
Example #17
Source File: base.service.ts    From nodejs-angular-typescript-boilerplate with Apache License 2.0 6 votes vote down vote up
constructor(
    private httpClient: HttpClient
  ) {
    this.httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json; charset=utf-8',
        'Access-Control-Allow-Origin': '*',
        'Cache-Control': 'no-cache'
      })
    };
    this.httpHeaders = new HttpHeaders(this.httpOptions);
  }
Example #18
Source File: twirp-transport.service.ts    From protobuf-ts with Apache License 2.0 6 votes vote down vote up
/**
 * Create Angular headers for a Twirp request.
 */
export function createTwirpRequestHeader(sendJson: boolean, meta?: RpcMetadata): HttpHeaders {
  let headers = new HttpHeaders();
  // add meta as headers
  if (meta) {
    for (let [k, v] of Object.entries(meta)) {
      if (typeof v == "string")
        headers = headers.append(k, v);
      else
        for (let i of v)
          headers = headers.append(k, i);
    }
  }
  // set standard headers (possibly overwriting meta)
  headers = headers.set('Content-Type', sendJson ? "application/json" : "application/protobuf");
  headers = headers.set('Accept', sendJson ? "application/json" : "application/protobuf, application/json");
  return headers;
}
Example #19
Source File: user-auth.service.ts    From data-annotator-for-machine-learning with Apache License 2.0 6 votes vote down vote up
public getBasicAuthToken() {
    this.http
      .get(`${this.env.config.annotationService}/api/v1.0/token`, {
        headers: new HttpHeaders().append('Authorization', this.loggedUser().token.access_token),
      })
      .subscribe(
        (res) => {
          const storedUser = JSON.parse(localStorage.getItem(this.env.config.serviceTitle));
          storedUser.token = res;
          localStorage.setItem(this.env.config.serviceTitle, JSON.stringify(storedUser));
          this.autoRefreshToken();
        },
        (err) => {
          this.sessionLifetimeSubject.next(SessionStatus.EXPIRED);
          this.logout();
        },
      );
  }
Example #20
Source File: wlhttp.service.ts    From WiLearning with GNU Affero General Public License v3.0 6 votes vote down vote up
uploadFiles(file: WlFile, url: string) {
    const headers = new HttpHeaders();
    headers.set('Access-Control-Allow-Origin', '*');

    const form = new FormData();
    form.append('file', file.blob, file.name);

    const req = new HttpRequest('POST', url, form, {
      reportProgress: true,
      headers,
    });

    return this.http.request(req).pipe(
      map(event => this.getEventMessage(event, file)),
      last(),
      catchError(this.handleError(file))
    );
  }
Example #21
Source File: http-extensions.service.ts    From distributed-compliance-ledger with Apache License 2.0 6 votes vote down vote up
postAny(url: string, body: any | null, params?: HttpParams, httpHeaders?: HttpHeaders): Observable<any> {
    return this.http.post(url, body, {
      responseType: 'text',
      params,
      headers: httpHeaders
    }).pipe(map(text => {
      const jsonObj: object = JSON.parse(text);
      return HttpExtensionsService.removeWrapper(jsonObj);
    }));
  }
Example #22
Source File: abstract.ts    From Smersh with MIT License 5 votes vote down vote up
getOptions(): { headers: HttpHeaders } {
    return {
      headers: new HttpHeaders({
        Authorization: `Bearer ${new Token().get()}`,
        'Content-Type': 'application/json; charset=utf-8',
      }),
    };
  }
Example #23
Source File: blogs.service.ts    From Collab-Blog with GNU General Public License v3.0 5 votes vote down vote up
httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': '',
    'Authorization': 'my-auth-token',
    'Access-Control-Allow-Origin': '*'
  })
}
Example #24
Source File: attribution.service.ts    From barista with Apache License 2.0 5 votes vote down vote up
public defaultHeaders = new HttpHeaders();
Example #25
Source File: agent.service.ts    From Developing-Multi-platform-Apps-with-Visual-Studio-Code with MIT License 5 votes vote down vote up
getOptions(): any{
    let opt = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
    return opt;
  }
Example #26
Source File: github-addon-provider.ts    From WowUp with GNU General Public License v3.0 5 votes vote down vote up
private getIntHeader(headers: HttpHeaders, key: string) {
    return parseInt(headers.get(key) ?? "", 10);
  }
Example #27
Source File: scanner.service.ts    From RoboScan with GNU General Public License v3.0 5 votes vote down vote up
public defaultHeaders = new HttpHeaders();
Example #28
Source File: oracle-explorer.service.ts    From bitcoin-s-ts with MIT License 5 votes vote down vote up
private getHeaders() {
    const headers = new HttpHeaders()
      .set(HOST_OVERRIDE_HEADER, this.oracleExplorer.value.host)
    return { headers }
  }
Example #29
Source File: api.service.ts    From blockcore-hub with MIT License 5 votes vote down vote up
private headers = new HttpHeaders({ 'Content-Type': 'application/json' });