标签: angular-httpclient

Angular 4 Http POST无效

我希望每个人都做得很好.我最近开始使用angular 4.4,我一直试图将数据发布到我的api服务器,但不幸的是它没有用.我花了两天时间,但仍然没有成功.并且已经尝试过6-7篇甚至来自angular.io的文章.我已经尝试了HttpHttpclient模块,但似乎没有任何工作.

问题是,每当我尝试将数据发布到我的服务器时,Angular都会生成http OPTIONS类型请求而不是 POST.

this.http.post('http://myapiserver.com', {email: 'adam@example.com'}).subscribe(
    res => {
        const response = res.text();
    }
);
Run Code Online (Sandbox Code Playgroud)

我也试图发送请求的自定义选项,但仍然没有成功.

const headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded' });
const options = new RequestOptions({ headers: headers });
options.method = RequestMethod.Post;
options.body = {name: 'Adam Smith'};
//options.body = JSON.stringify({name: 'Adam Smith'}); // i also tried this
//options.body = 'param1=something&param2=somethingelse'; // i also tried this
Run Code Online (Sandbox Code Playgroud)

我使用的是ASP.NET核心2.0,但由于它不起作用我也试过简单的PHP代码,这里是php的服务器端代码.它也没有用.

<?php
print_r($_POST);
?>
Run Code Online (Sandbox Code Playgroud)

注意:Cors也在服务器上启用.另外,我也试过简单的get请求,它的工作非常好.

我真的很感激一些帮助.

提前致谢

javascript http-post angular-http angular angular-httpclient

6
推荐指数
2
解决办法
3万
查看次数

通过 Angular HttpClient 发送二进制文件

我想发送一个带有来自文件的二进制数据的 http POST 请求。当我通过 postman->Body->Binary->Choose file 执行此操作时,我得到了成功的服务器响应。看图片:

在此处输入图片说明

但我不知道如何通过 Angular HttpClient 做到这一点。我怎样才能完成以下工作:

set processImage(event) {
    console.log(event);
    let files: FileList = event.target.files;
    let file = files[0]; 
    //send the file as a binary via httpClient
    ....
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient

6
推荐指数
1
解决办法
7236
查看次数

Angular httpClient拦截器错误处理

在阅读了有关http客户端错误处理的有关角度的文档后,我仍然不明白为什么我没有从服务器捕获带有以下代码的401错误:

export class interceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('this log is printed on the console!');

        return next.handle(request).do(() => (err: any) => {
            console.log('this log isn't');
            if (err instanceof HttpErrorResponse) {
                if (err.status === 401) {
                    console.log('nor this one!');
                }
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

在控制台日志上,我也得到了:

zone.js:2969 GET http:// localhost:8080 / test 401()

core.js:1449错误HttpErrorResponse {标题:HttpHeaders,状态:401,statusText:“确定”,url:“ http:// localhost:8080 / test ”,确定:否,…}

angular-http-interceptors angular angular-httpclient angular6

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

Angular 6:HttpHeaders 无法在 Chrome 和 IE11(而不是 Firefox)中读取 null 的属性“长度”

在我的Angular6应用程序下,我使用HttpClient和一些标头注入到我的 htpp 调用以从我的后端服务器获取数据:

我的服务:

@Injectable()
export class LoadUserInfosService {

  public _headers = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(private httpClient: HttpClient) {}

  getUserPnsInfos(cuid): Observable<object> {
    const headers = this._headers.append('login', login);
    return this.httpClient.get(myBackUrl, {headers: headers});
  }
}
Run Code Online (Sandbox Code Playgroud)

我订阅的组件:

loadUserInfosFromPns(login) {
    this.loadUserInfosService.getUserPnsInfos(login).subscribe(infos => {
      let receivedInfos: any;
        receivedPnsInfos = infos ;
        console.log(receivedPnsInfos);
        if (pnsInfos !== null && receivedPnsInfos.cuid === cuid ) {
        } else {
          this.router.navigate(['unauthorized'], {skipLocationChange: true});
        }
      },
      error => {
        console.log(error);
      });
  }
Run Code Online (Sandbox Code Playgroud)

在 Chrome 或 IE11 上运行时,我收到一些关于我的请求标头的错误: …

javascript rest google-chrome angular angular-httpclient

6
推荐指数
1
解决办法
6413
查看次数

调用Bing Maps Locations REST方法时出现Angular HttpClient问题

我现在已经调用了使用Angular 4 Http服务制作的Bing Maps,它正常工作:

this.http.get("{absolute URL of Bing Maps REST Locations, with options and key}")
Run Code Online (Sandbox Code Playgroud)

我正在尝试更改调用以使用Angular 4.3中引入的HttpClient服务,但在尝试相同的代码时:

this.httpClient.get("{absolute URL of Bing Maps REST Locations, with options and key}")
Run Code Online (Sandbox Code Playgroud)

然后请求与预检OPTIONS请求一起发送,而bing map显然拒绝它.

我试图观察请求而不是正文,请求文本响应,并强制Accept标头文本,但没有成功.

Http请求的标头(工作):

Accept: application/json, text/plain, */*
Origin: http://localhost:4200
Referer: http://localhost:4200/
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Run Code Online (Sandbox Code Playgroud)

HttpClient请求的标头(不工作):

Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Run Code Online (Sandbox Code Playgroud)

有关为什么HttpClient请求与Http请求如此不同的任何想法?如何强制HttpClient跳过预检OPTIONS请求?我错过了什么吗?

在此先感谢您的帮助

bing-maps angular angular-httpclient

6
推荐指数
1
解决办法
185
查看次数

当 API 返回 204 状态代码时,httpclient 响应为 null

我有一个休息端点/Products/latest,如果没有产品,它会返回 204,以及以下通用角度服务:

  getFromAPI(url: string) {
    const params = new HttpParams();

    return this.http
        .get(url, { params: params })
        .catch((err: HttpErrorResponse) => {
            console.error(`Backend returned code ${err.status}, body was: ${err.error}`);                  
            return Observable.of([]);
        });
  }
Run Code Online (Sandbox Code Playgroud)

 getFromAPI() {
        return this.masterService.get('/Products/latest').map((res: Response) => {
            if (res.status === 204) {
                return Observable.of([]);
            } else {
                return res;
            }

        });
    }
Run Code Online (Sandbox Code Playgroud)

但是,当服务产生 204 代码时,我收到以下错误:

类型错误:无法读取 null 的属性“状态”

这怎么会发生?如果 API 以 204 响应,为什么整个响应为空?

angular angular-httpclient

6
推荐指数
1
解决办法
4928
查看次数

Angular 7 Http 删除 api 句柄主体?

我正在尝试从 Angular 7 前端与有点 REST API 交谈。

要从集合中删除某些项目,除了删除唯一 ID 之外,我还需要发送一些其他数据,即身份验证令牌、一些集合信息和一些辅助数据。

但是,Angular 7 的 Http 模块并不完全同意带有正文的 DELETE 请求,并尝试发出此请求。

这是我的api:

DELETE /user/verifications

body {
  "doc_type": "govt_id",
  "doc_id": "5beedd169db947867b710afd"
}
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient

6
推荐指数
2
解决办法
2万
查看次数

取消 ngrx 效果中待处理的休息呼叫

在我的 Angular 应用程序中,我有一个上传页面。上传由服务处理并由 NGRX 效果触发。

// service 
public upload(file: File): any {
  const formData: FormData = new FormData();
  formData.append('file', file, file.name);

  // create a http-post request and pass the form
  // tell it to report the upload progress
  const request = new HttpRequest('POST', url, formData, {
    reportProgress: true
  });

  return this.httpClient.request(request);}


// Effect
@Effect({ dispatch: false })
  uploadFile = this.actions
    .ofType(ActionTypes.UploadFile)
    .map(toPayload)
    .switchMap(file =>
      this.service.upload(file).map(event => {
        if (event.type === HttpEventType.UploadProgress) {
          // calculate the progress percentage
          const percentDone = …
Run Code Online (Sandbox Code Playgroud)

rxjs ngrx ngrx-effects angular angular-httpclient

5
推荐指数
0
解决办法
1964
查看次数

如何将 httpClient 注入到实例化服务中?

我在 app.module.ts 中实例化 MyService,并在我的代码中提供它。

但是,我希望 MyService 使用 httpClient,并且我无法以角度惯用方式实例化 httpClient 以作为参数传递给 MyService。我不确定在 MyService 中访问 httpClient 的正确方法是什么。

我考虑过直接实例化 httpClient ,然后将其作为参数传递给我的服务。然而,这似乎造成了循环依赖。我也尝试过弄乱注入器,但显然 Angular 团队特别建议不要这样做。我强烈地觉得我错过了一些简单的东西。

应用程序模块.ts

imports: [
    ...
    httpClientModule
    ...
],

function MainServiceFactory() {
    return new MyService();
}
...
providers: [{
    provide: MyService,
    useFactory: MainServiceFactory
}],
...
Run Code Online (Sandbox Code Playgroud)

MyService.ts

...
constructor(private http : HttpClient) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果没有实例化并作为 httpClient 的参数传递:我自然会收到“app.module.ts 中的错误,预期 1 个参数”!通过实例化,我打破了角度建议。

编辑: 我忽略了指定我确实导入了 httpClientModule

angular angular-httpclient

5
推荐指数
1
解决办法
8569
查看次数

RxJS mergeMap 运算符内部的错误处理

当我使用 Angular HttpClient 发出 GET 请求时,我会得到一个可观察的数据并在 RxJS 运算符 mergeMap 中处理它。

现在,一次又一次地抛出 404,我想抓住它。最后,浏览器控制台中不应出现任何错误消息,并且应使用流的下一个值来处理管道。

有这种可能吗?我没有用catchError()来管理它。

这是我的代码的简化版本:

    ...
    this.service1.getSomeStuff().pipe(
          mergeMap((someStuff) => {
            return from(stuff);
          }),
          mergeMap((stuff) => {
            return this.service2.getMoreStuff(stuff.id); // Here I need some error handling, if 404 occurs
          }),
          mergeMap((things) => {
            return from(things).pipe(
              mergeMap((thing) => {
                if (allLocations.some(x => x.id === metaData.id)) {
                  return this.service2.getMore(thing.id, thing.type, thing.img_ref);
                }
              }),
              map((thing) => {
              ...
Run Code Online (Sandbox Code Playgroud)

更新:添加了 catchError() 方法

我尝试了这种方式,但是没有检测到错误,并且下一个 mergeMap 不起作用(IDE 不再识别thing.id、thing.type、th​​ing.img_ref等参数):

...
this.service1.getSomeStuff().pipe(
      mergeMap((someStuff) => {
        return from(stuff);
      }), …
Run Code Online (Sandbox Code Playgroud)

subscription observable rxjs angular angular-httpclient

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