@angular/common/http#HttpResponse TypeScript Examples

The following examples show how to use @angular/common/http#HttpResponse. 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: fake-backend.service.ts    From ng-conf-2020-workshop with MIT License 6 votes vote down vote up
registerHandle(newUser: StorageUser, update = false) {
        const duplicateUser = this.users.find(user => user.email === newUser.email);
        if (duplicateUser && !update) {
            return throwError({ error: { message: 'Account with email "' + newUser.email + '" already exists' } });
        }
        if (update && duplicateUser) {
            Object.assign(duplicateUser, newUser);
        } else {
            this.users.push(newUser);
        }
        this.localStorage.setItem('users', JSON.stringify(this.users));

        const body = this.getUserJWT(newUser);

        return of(new HttpResponse({ status: 200, body: this.generateToken(body) }));
    }
Example #2
Source File: authorization.service.ts    From alura_angular_rxjs_1 with MIT License 6 votes vote down vote up
login(user: UserLogin): Observable<object | User> {
    const loginSubject = new Subject<User>();
    this.requestToken(user).subscribe(
      (response: HttpResponse<User>) => {
        const { body: loggedUser } = response;
        loggedUser.token = response.headers.get('x-access-token');
        this.saveUserInfo(loggedUser);
        loginSubject.next(loggedUser);
      },
      (error) => {
        loginSubject.error(error);
      }
    );
    return loginSubject.asObservable();
  }
Example #3
Source File: default-headers.interceptor.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth token from the service.

    // Clone the request and replace the original headers with
    // cloned headers, updated with the authorization.
    // const cloneReq = req.clone({
    //   headers: req.headers.set("startTimestamp", Date.now().toString()),
    // });
    const start = Date.now();
    const method = req.method;
    const url = req.urlWithParams;

    // send cloned request with header to the next handler.
    return next.handle(req).pipe(
      tap((response: any) => {
        try {
          if (response instanceof HttpResponse) {
            const t = Date.now() - start;
            console.log(`[${method}] ${url} ${response.status} ${t}ms`);
          }
        } catch (e) {
          console.error(e);
        }
      })
    );
  }
Example #4
Source File: fileadmin.service.ts    From CloudeeCMS with Apache License 2.0 6 votes vote down vote up
public upload(files: Set<File>, s3uploadPath: string, s3policy: any, CCMaxAge: string): { [key: string]: Observable<number> } {
        const status = {}; // observables map
        let maxAge = CCMaxAge;
        if (!maxAge || maxAge === '') { maxAge = '259200'; }
        files.forEach(file => {
            const formData: FormData = new FormData();
            formData.append('Content-Type', file.type);
            // tslint:disable-next-line: forin
            for (const f in s3policy.fields) { formData.append(f, s3policy.fields[f]); } // inherit all fields from policy
            formData.append('ACL', 'public-read'); // must appear before file contents!
            formData.append('Cache-Control', 'max-age=' + maxAge);
            const targetFilename = s3uploadPath + file.name;
            console.log('upload', targetFilename);
            formData.append('key', targetFilename);
            formData.append('file', file); // , file.name);

            const req = new HttpRequest('POST', s3policy.url, formData, { reportProgress: true });
            const progress = new Subject<number>();

            // IMPORTANT: exclude POST upload URL from httpinterceptor!!
            this.http.request(req).subscribe(event => {
                if (event.type === HttpEventType.UploadProgress) {
                    const percentDone = Math.round((100 * event.loaded) / event.total);
                    progress.next(percentDone); // update progress bar
                } else if (event instanceof HttpResponse) {
                    progress.complete(); // done uploading this file
                }
            });

            status[file.name] = {
                progress: progress.asObservable(),
                s3key: targetFilename,
                nm: file.name
            };
        });
        return status;
    }
Example #5
Source File: rest.service.ts    From App with MIT License 6 votes vote down vote up
// tslint:enable:typedef

	createRequest<T>(
		method: RestService.Method,
		route: string,
		options?: Partial<RestService.CreateRequestOptions>,
		apiVersion: RestService.ApiVersion = 'v2'
	): Observable<HttpResponse<T> | HttpProgressEvent> {
		if (this.platformId === 'server' && !options?.runOnSSR) {
			return EMPTY;
		}

		const uri = (route.startsWith('http') ? '' : this.BASE[apiVersion]) + route;
		const opt = {
			observe: 'events',
			headers: {
				...(options?.headers ?? {}),
				Authorization: (options?.auth && this.clientService.getToken()?.length > 0) ? `Bearer ${this.clientService.getToken()}` : ''
			},
			reportProgress: true
		} as any;

		return of(method).pipe(
			switchMap(m => iif(() => (m === 'get') || (m === 'delete'),
				this.httpService[m](uri, opt),
				this.httpService[m as RestService.BodyMethod](uri, options?.body ?? {}, opt)
			))
		).pipe(map((x: any) => x as (HttpResponse<T> | HttpProgressEvent)));
	}
Example #6
Source File: project-api.service.ts    From barista with Apache License 2.0 5 votes vote down vote up
public projectIdStatsSeveritiesGet(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<ProjectDistinctSeverityDto>>>;
Example #7
Source File: scanner.service.ts    From RoboScan with GNU General Public License v3.0 5 votes vote down vote up
public stopSession(sessionId: number, xFields?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Status>>;
Example #8
Source File: project-api.service.ts    From barista with Apache License 2.0 5 votes vote down vote up
public projectIdStatsVulnerabilitiesGet(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<ProjectDistinctVulnerabilityDto>>>;
Example #9
Source File: scanner.service.ts    From RoboScan with GNU General Public License v3.0 5 votes vote down vote up
public startScan(sessionId: number, xFields?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Status>>;
Example #10
Source File: vulnerability-status-deployment-type-api.service.ts    From barista with Apache License 2.0 5 votes vote down vote up
public vulnerabilityStatusDeploymentTypePost(vulnerabilityStatusDeploymentType: VulnerabilityStatusDeploymentType, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<VulnerabilityStatusDeploymentType>>;