Ionic 2:如何处理来自POST的响应

时间:2017-01-17 22:35:57

标签: angularjs json http ionic-framework

我觉得自己像个傻瓜。 我想通过一个POST给我一个json的问题。 如何访问其中一个json字段并发送到调用它的页面?

我有这个提供者:

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

@Injectable()
export class AuthService {
  data: any;
  result: any;
  http: Http;

  public login(credentials) {

    if (credentials.email === null || credentials.password === null) {
      return Observable.throw("Please insert credentials");
    } else {
      return Observable.create(observer => {
        // At this point make a request to your backend to make a real check!
        this.data = {api_token: "asdfg", http_id: credentials.email, http_pass: credentials.password};
        this.http.post('http://mywebsite/api/login', JSON.stringify(this.data), {headers: {'Content-Type': 'application/json'}})
        .map(res => res.json())

        let access = (credentials.password === "pass" && credentials.email === "email");
        observer.next(access);
        observer.complete();
      });
    }
  }

  public logout() {
    return Observable.create(observer => {
      observer.next(true);
      observer.complete();
    });
  }
}

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您尝试从响应中获取数据,这就足够了

public login(credentials) {
if (credentials.email === null || credentials.password === null) {
  return Observable.throw("Please insert credentials");
} else {
    let data = {api_token: "asdfg", http_id: credentials.email, http_pass: credentials.password};
    return this.http.post('http://mywebsite/api/login', JSON.stringify(data), {headers: {'Content-Type': 'application/json'}})
    .map(res => res.json())
}}

在组件中,您可以将其作为

进行访问
provider.login(cred).subscribe(res => { 
console.log(res) },
err => {
console.log(err)
)