标签: angular-httpclient

从 @Angular/http 迁移到 @Angular/common/http

我正在将 angular-cli 应用程序从“@angular/http”迁移到“@angular/common/http”,但在使其正常工作时遇到一些问题。

我有一个函数可以向我的 API 发出请求并返回以下 json。

{"Categories":[
   {"name":"my first category","routetype":"category"},
   {"name":"my second category","routetype":"category"}
]}
Run Code Online (Sandbox Code Playgroud)

我正在将其映射到类

export class Category {
    name: string;
    routetype: string;
}
Run Code Online (Sandbox Code Playgroud)

当前代码(工作):

import { Http, Response } from '@angular/http';
...
getCategories(context: SiteContext): Observable<Array<Category>> {
    return this.http.get(routes.getCategories(context), { cache: true })
      .map((res: Response) => <Array<Category>>res.json().Categories)
      .do(data => console.log(data))
      .catch(this.handleError);
  }
Run Code Online (Sandbox Code Playgroud)

新代码(不起作用)。

import { HttpClient } from '@angular/common/http';
...
getCategories(context: SiteContext): Observable<Array<Category>> {
    return this.httpClient.cache().get(routes.getCategories(context))
      .map((res: Response) => <Array<Category>>res.json().Categories)
      .do(data => console.log(data))
      .catch(this.handleError);
  }
Run Code Online (Sandbox Code Playgroud)

在 vs.code 中我收到以下错误消息:

[ts] …
Run Code Online (Sandbox Code Playgroud)

angular-cli angular-httpclient

4
推荐指数
1
解决办法
2728
查看次数

使用 HttpClient 对本地 json 文件进行 POST 请求

我的 Angular 应用程序中的资产中有一个名为fake.jsonjson的文件。这个文件的路径是这样的。

MyApp => src => 资产 => json => fake.json

我想POST在应用程序文件夹内的组件中使用 HttpClient 向此文件发出请求。

MyApp => src => 应用程序 => 统计 => stats.component.ts

组件源代码

export class StatisticsComponent {

  persons: Person[];

  options = {
    sDom: 'rt<"bottom"p>',
    pagingType: 'full_numbers',
    pageLength: 10,
    serverSide: true,
    processing: true,
    ajax: (dataTablesParameters: any, callback) => {
      this.http
        .post<DataTablesResponse>(
          './../../assets/json/fake.json',
          dataTablesParameters, {}
        ).subscribe(resp => {
          this.persons = resp.data;
          callback({
            recordsTotal: resp.recordsTotal,
            recordsFiltered: resp.recordsFiltered,
            data: []
          });
        });
    },
    columns: [
      { data: …
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient

4
推荐指数
1
解决办法
8442
查看次数

Angular 6:如何获取响应状态代码

如何获取服务代码?我尝试下面的代码,但它没有记录任何内容。

在 service.ts 文件中。

constructor(private http: HttpClient) { }

postForgotPass(email): Observable<Response> {

return this.http.post<Response>(envi.apiUrl +'/user/forgotpassword', {
  "email": email,
  "headers": headers,
  observe: 'response'

})
}
Run Code Online (Sandbox Code Playgroud)

在我的 component.ts 文件中

sendForgotPass() {
 return this.service.postForgotPass(this.emailFormControl.value)
    .subscribe(
      res => {
        console.log(res.status);
      })
    }
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient

4
推荐指数
1
解决办法
1万
查看次数

当字段未触及时,Angular 反应形式返回空值

在我的用例中,当用户单击编辑按钮时,Angular 对后端进行 HTTP 调用并检索对象,然后在 EDIT 表单上填充这些值。用户可以更新或保持字段不变。当单击update按钮时,Angular 应该获取表单中存在的所有这些值并将它们发送到后端。所以,这是问题所在,在将值加载到编辑页面表单并更新某些字段并保留某些字段不变后,未修改的值会变为空。这真的很奇怪

产品-edit.component.html

<div *ngIf="productDataAvailable()">
  <h2>Update Product</h2>
  <br/>
  <form [formGroup]="productForm">
    <div class="form-group">
      <label for="id">Product Id</label>
      <input class="form-control" formControlName="id" id="id" type="text" value="{{product.id}}">

      <small class="form-text text-muted" id="emailHelp"></small>
    </div>
    <div class="form-group">
      <label for="name">Name</label>
      <input class="form-control" formControlName="name" id="name" type="text" value="{{product.name}}">
    </div>
    <div class="form-group">
      <label for="description">Description</label>
      <input class="form-control" formControlName="description" height="100" id="description" required type="text"
             [value]="product.description" width="200">
    </div>
    <div class="form-group">
      <label for="currency">Price</label> <br/>
      <label>
        <select (load)="loadCurrencies()" class="form-control"  [value]="product.price.currency.symbol" formControlName="currency" id="currency" name="currency">
          <option *ngFor="let currency of currencies" value={{currency.id}}>
            {{currency.name}}
          </option>
        </select> …
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient angular6 angular7

4
推荐指数
1
解决办法
6262
查看次数

如何在 Angular 中获取 HttpClient.Post 请求的响应头

我正在使用 angular 7,我需要从服务文件中的给定 API 获取“响应头”,而不使用“订阅”。请帮助我

我尝试过使用许多谷歌答案,但没有一个有效。我无法在 service.ts 文件中使用订阅,因为我在 component.ts 文件中收到错误,因为我们无法使用订阅两次

login(email: string, password: string ) {
this.email = email;
this.password = password;


return this.http.post<any>(`this.url/auth/login`, { email, password})
.pipe(map(user => {
var currentuser:any = { user: user.user, token: user.token};
if (currentuser && user.token) {
localStorage.setItem('currentUser', JSON.stringify(currentuser));
this.currentUserSubject.next(currentuser);
 }
return user;
 }));
Run Code Online (Sandbox Code Playgroud)

}

预期结果 :

需要为上面的api获取“”响应头.. 注意:“响应头”的意思是——内容长度、令牌、Content-Type、Etag等

实际结果 :

我只得到正文而不是标题

angular angular-httpclient

4
推荐指数
1
解决办法
8384
查看次数

Angular:捕获连接超时且无互联网连接 HTTP 错误

我正在尝试使用较新的 Angular 的 HTTP 客户端为 HTTP 请求添加错误处理: https: //angular.io/guide/http

在文档中,它说错误处理是按如下方式完成的:

return this.http.get('https://api.example.com/foo')
    .pipe(
      catchError(this.handleError)
    );

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.log('Client side error:', error.error)
    // TODO: how do I catch specific client side errors?
  } else {
    console.log('Back-end error:', error.error)
  }
  // return an observable with a user-facing error message
  return throwError('Something bad happened; please try again later.');
};
Run Code Online (Sandbox Code Playgroud)

处理后端错误非常简单。但是,我希望能够捕获特定的客户端错误,例如:

  • 连接超时 (net::ERR_CONNECTION_TIMED_OUT)
  • 没有网络连接

我怎样才能捕获这些特定的客户端错误? …

angular angular-httpclient

4
推荐指数
1
解决办法
6180
查看次数

类型错误:无法读取未定义的属性“长度”(Angular 8)(标头)

当我尝试注销时出现此错误。

`core.js:6014 ERROR TypeError: Cannot read property 'length' of undefined
    at http.js:165
    at Array.forEach (<anonymous>)
    at HttpHeaders.lazyInit (http.js:153)
    at HttpHeaders.init (http.js:274)
    at HttpHeaders.forEach (http.js:376)
    at Observable._subscribe (http.js:2342)
    at Observable._trySubscribe (Observable.js:42)
    at Observable.subscribe (Observable.js:28)
    at subscribeTo.js:20
    at subscribeToResult (subscribeToResult.js:7)`
Run Code Online (Sandbox Code Playgroud)

但是当我从邮递员发送 HTTP 请求时,代码就可以工作了。我在使用邮递员时成功退出

我的认证服务

`logout(user){
    let headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': this.token }); //this.token is the value of token(eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX...)
  let options = { headers: headers };
    localStorage.clear()
    this.token=null;
    return this.http.post<response>('http://localhost:3000/users/logout',null,options).pipe(map(res=>{
      console.log(res)
       return res
    }))}
Run Code Online (Sandbox Code Playgroud)

` 这是我订阅此 http 请求的代码:

 onLogout(){ …
Run Code Online (Sandbox Code Playgroud)

authentication angular angular-httpclient

4
推荐指数
1
解决办法
3988
查看次数

在 Angular 2+ 中订阅后 API 调用失败时如何重试

我正在调用 API 来获取随机详细信息。问题是,有时我会收到 502 错误作为网关错误,并且它也可能由于网络连接错误而中断。下面是我的API调用代码

// COMPONENT API CALL SUBSCRIBE
     this._service.post('randomAPI/getdetails', filters).subscribe((response: any) => {
     this.itemList = response;    
   });

// SHARED SERVICE
     post<T>(url: string, body: any): Observable<T> {
     return this.httpClient.post<T>(url, body);
   } 
Run Code Online (Sandbox Code Playgroud)

每当我收到 500 或 502 服务器错误时,我都会使用拦截器路由到错误页面以通知用户服务器问题。

相反,如果失败,我可以让 API 在组件级别或拦截器级别再尝试一次,然后路由到错误页面吗?

// INTERCEPTOR
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(catchError(error => {
        if (error.status === 401 || error.status === 400 || error.status === 403) {
            this.router.navigateByUrl('abort-access', { replaceUrl: true });
        } else if (error.status === 500 || error.status === 502) …
Run Code Online (Sandbox Code Playgroud)

interceptor rxjs angular angular-httpclient retrywhen

4
推荐指数
1
解决办法
1万
查看次数

将 http 选项设置为 'responseType: 'text'' 会导致使用 Angular HttpClient 的 http post 请求编译失败

虽然 Angular HttpClient 中有一个重载的 API 方法,如下所示:

 post(url: string, body: any | null, options: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: 'body';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType: 'text';
        withCredentials?: boolean;
    }): Observable<string>;
Run Code Online (Sandbox Code Playgroud)

当我尝试使用选项 'responseType: 'text'' 执行以下发布请求时,我收到编译器错误,指出“没有重载与此调用匹配。...”

const opts = {
      headers: new HttpHeaders({
        'Accept': 'text/html, application/xhtml+xml, */*',
        'Content-Type': 'text/plain; charset=utf-8'
      }),
      responseType: 'text'
    };
    return this.http.post<string>('url', null, opts);
Run Code Online (Sandbox Code Playgroud)

注意:我明智地传递 null 作为响应主体,因为我的 API 不接受主体。我在这里做的可能是错的吗?

更新 根据 Michael D 的要求添加完整的错误消息 …

angular angular-httpclient angular9

4
推荐指数
1
解决办法
1万
查看次数

角度句柄可处理500个服务器错误

如何修改我的http调用以处理(捕获)500个服务器错误。我尝试调用API,但在函数的“ err”部分收到“ 500(内部服务器错误)”。我希望能够在可能的情况下捕获它,但不确定如何执行。是否有一种简单的方法?

  call_http() {
    this.http.get<any>('/api/goes/here').subscribe(data => {
      this.result = data;
    },
      err => {
        console.log(err);
      });
  }
Run Code Online (Sandbox Code Playgroud)

我没有使用任何标头,映射,错误处理程序等。这只是一个基本调用。

angular angular-httpclient

3
推荐指数
4
解决办法
5507
查看次数