Angular 2 HTTP只需要JSON

时间:2016-11-28 04:55:06

标签: angularjs json

我正在使用angular2 HTTP模块从SoundCloud API获取数据。我知道如何用observables获取数据:

   return this._http.get(`${API_BASE_URL}/users/${FEAT_USER_ID}/favorites?${CLIENT_ID_PARAM}`)
  .map((res:Response) => res.json())
  .catch((error:any) => Observable.throw(error.json().error || 'Server error'))

如何在不使用observables /必须订阅获取数据的情况下返回JSON对象?

2 个答案:

答案 0 :(得分:1)

你可以做的是

 import 'rxjs/add/operator/toPromise';

然后

 return this.http.get(this.publishersUrl)
               .toPromise()
               .then(response => response.json().data) 
               .catch(this.handleError);

请阅读the link部分:回到承诺

答案 1 :(得分:1)

创建服务,例如查看我的用户服务

    import { Injectable } from '@angular/core';
import {Http, Headers} from "@angular/http";
import {Observable} from "rxjs";
import {AuthService} from "./auth.service";
import {User} from "./user";

@Injectable()
export class UserService {


  headers = new Headers({
    "Content-Type": "application/json",
    'Authorization': this.authService.getToken(),
  });

  serverUrl = "http://0.0.0.0:3000/api";

  constructor(private http:Http, private authService: AuthService) {



  }


  login(username: string, password: string): Observable<any>{

    let url = this.serverUrl + "/accounts/login?include=user";

    return this.http.post(url, {username: username, password: password}, {headers: this.headers}).map(res => res.json()).catch(err => {

      return Observable.throw(err);
    })
  }

  register(user: User): Observable<any>{
    let url = this.serverUrl + "/accounts";
    this.headers.delete('Authorization');

    return this.http.post(url, user, {headers: this.headers}).map(res => res.json()).catch(err => {

      return Observable.throw(err);
    });
  }

  logout(): Observable<any>{

    let url = this.serverUrl + '/accounts/logout';
    let data = {accessTokenID: this.authService.getToken()};
    return this.http.post(url, data, {headers: this.headers}).map(res => res.json()).catch(err => {
     return Observable.throw(err);
    });
  }

}

现在在组件中你可以调用

this.userService.login(user.username, user.password).subscribe(response => {

      console.log(response);


    }, err => {

      console.log(err);
    })

查看github上的代码:https://github.com/tabvn/angular-blog 视频教程:https://www.youtube.com/watch?v=sFpwxTdy9gQ&list=PLFaW_8zE4amNEdKZOJD3P_GeV3Hgva7RD