如何使用离子本机http而不是有角度的http

时间:2019-05-16 03:03:56

标签: angular typescript http ionic3

有人可以帮我一些代码吗,我正在尝试使用离子本机HTTP, 但它不起作用。从http.post访问响应时,我不断出错。我得到的错误是:

  

类型'HTTPResponse'上不存在属性'json'

  

类型“ Promise”上不存在属性“ subscribe”。

当我使用import { Http } from '@angular/HTTP'时一切正常,但由于某些原因有时在设备上HTTP.post不起作用,所以这就是我要使用import { HTTP } from '@ionic-native/http';的原因 下面我同时包含了这两个代码,请有人帮助我。

这很好:

import { Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

import {Auth0Config as Config} from '../config/auth0';

@Injectable()
 export class Auth {
 URL: String;

   constructor(public http: Http) {
     this.url = Config.AUTH0_DOMAIN;
   }

   login(user: String, pass: String) {
    let endpoint = "/oauth/token";
    let body = {
        "client_id": Config.AUTH0_CLIENTID,
        "username": user,
        "password": pass,
        "connection": Config.AUTH0_CONNECTION,
        "grant_type": "password"
    };
    return this.http.post(this.url + endpoint, body).map(res => res.json());
  }

  getProfile(token: String) {
    let endpoint = "/userinfo";
    let query = "?access_token=" + token;
    return this.http.get(this.url + endpoint + query).map(res => res.json());
  }

}

不起作用

import {Injectable} from '@angular/core';
import {HTTP} from '@ionic-native/http';
import 'rxjs/add/operator/map';

import {Auth0Config as Config} from '../config/auth0';

@Injectable()
export class Auth {
URL: String;

  constructor(public http: HTTP) {
    this.url = Config.AUTH0_DOMAIN;
  }

  login(user: String, pass: String) {
    let endpoint = "/oauth/token";
    let body = {
        "client_id": Config.AUTH0_CLIENTID,
        "username": user,
        "password": pass,
        "connection": Config.AUTH0_CONNECTION,
        "grant_type": "password"
    };
    return this.http.post(this.url + endpoint, body, {}).then(res => {
        var res = res.json()
    });
  }

  getProfile(token: String) {
    let endpoint = "/userinfo";
    let query = "?access_token=" + token;
    return this.http.get(this.url + endpoint + query, {}, {}) //.map(res => res.json());
  }

}

1 个答案:

答案 0 :(得分:0)

问题在这里:

  var res = res.json()

角度http重新调整Promise<Response>

原生返回Promise<HTTPResponse>

使用此行代替

 var res = res

并检查此链接 Angular HttpClient: Convert HttpResponse to Response