从Http observable获取数据后,angular 2 rc4创建变量

时间:2016-07-28 22:33:55

标签: angular angular2-http

我有点新的angular2,我希望你可以帮助我,我很确定它一定是简单的东西,但这是交易我正在制作一个服务,可以处理http调用,但它需要在数据加载后应用一些过滤器再次向api服务器询问新的参数基本上我想让angular2处理那部分

更新**

  

服务

     

httpHandler(type,model){var token = this.LoginService.JwtDecoded(); var authHeader = new Headers(); authHeader.append('Authorization', 'Bearer ' + token);

 return this.http.get('http://127.0.0.1/api/service/'+model, {
      headers: authHeader
      })
  .map((res: Response) => res.json());    }
     

组件

this.Request.httpHandler('get','receiver/')
.subscribe(
    data => this.data = data, <-- from here
    err => this.error = 'there is a mistake!',
    () => console.log(this.data) <-- this one is outputing just what i want
  );
console.log(data); <-- i wanna output the same result in here

那么,我怎样才能将api结果捕获到变量中?

更新** 我想输出&#39; this.data&#39;在外部订阅,奇怪的是我可以输出内部订阅和在HTML中,但我需要在输出html之前用json做一些东西..任何想法的人?谢谢!

感谢您的时间,非常感谢。

1 个答案:

答案 0 :(得分:2)

创建服务以获取数据

// xyz.service.ts

import {Injectable} from '@angular/core';

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

@Injectable()
export class DataService {
  private url = `receiver/`;

  constructor(private http: Http) {
  }

  getData(): Observable<any> {
    return this.http.get(this.url)
      .map((res: Response) => res.json());
  }
}

现在在组件中使用该服务。

//xyz.component.ts

import {Component, OnInit} from '@angular/core';

import {DataService} from './xyz.service';

import {HTTP_PROVIDERS} from '@angular/http';

@Component({
  selector: 'app-home-content',
  templateUrl: 'xyz.component.html',
  styleUrls: ['xyz.component.scss'],
  providers: [DataService, HTTP_PROVIDERS]
})
export class HomeContentComponent implements OnInit {
  private data: Object;

  constructor(private _dataService: DataService) {
  }

  ngOnInit() {
    this._dataService.getData().subscribe(data => {
      this.data = data;
    });
  }
}

现在,数据将在this.data

中提供