无法在角度2中运行httpClient帖子

时间:2018-01-31 17:23:03

标签: angular

我是棱角分明的新手,我不得不向外部api写一个帖子请求: 这就是我的尝试:

import { Component } from '@angular/core';
import {HttpClientModule} from "@angular/common/http";
import {HttpParams} from "@angular/common/http";
import { OnInit } from '@angular/core';

@Component({
  selector: 'mobile',
  templateUrl: './mobile.component.html',
  styleUrls: ['./../app.component.css']
})

export class MobileComponent implements OnInit {

  constructor(private http: HttpClient){

    ngOnInit(): void {
      const postData = {mobile: 'MyNumber'};
      this.http.post('MyAPI', postData, {
        headers: new HttpHeaders().set('x-mobile-token', 'MyToken'),
      }).subscribe();
    }
  }
}

但是我在broswer的黑色叠加层上得到以下内容:

Failed to compile.

./src/app/components/mobile.component.ts
Module parse failed: Unexpected token (24:18)
You may need an appropriate loader to handle this file type.
|         void {
|             const: postData = { mobile: 'MyNumber' },
|             this: .http.post('MyAPI', postData, {
|                 headers: new HttpHeaders().set('x-mobile-token', 'MyToken'),
|             }).subscribe(console.log('We are here!'))
 @ ./src/app/app.module.ts 13:25-65
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts

我缺少什么?

2 个答案:

答案 0 :(得分:3)

是的,Saj说的是,你在构造函数中使用了错误的名字。您导入了HttpClientModule但注入了HttpClient。

你也缺少HttpHeaders并导入了你从未使用的HttpParams。应该是:

import { HttpClient, HttpHeaders} from "@angular/common/http";

constructor(private http: HttpClient){ }

答案 1 :(得分:2)

ngOnInit 应放在构造函数外部,

 constructor(private http: HttpClient){      
 }

 ngOnInit(): void {
      const postData = {mobile: 'MyNumber'};
      this.http.post('MyAPI', postData, {
        headers: new HttpHeaders().set('x-mobile-token', 'MyToken'),
      }).subscribe();
  }

还建议将post请求放在服务中并在组件内订阅。

修改

正如大卫提到的那样,您应该导入 HttpClient ,而不是 HttpClientModule

 import { HttpClient, HttpHeaders} from "@angular/common/http";

constructor(private http: HttpClient){ }