曾服务http.get通话结束后,部分执行功能

问题描述 投票:11回答:4

我有真正的麻烦缠绕我的周围观测和订阅头angular2。我目前遇到的问题是以下几点:

我有一个包含方法,从API发布和获取数据的服务。该服务被注入到一个组件,它直接调用服务的那些方法。然后服务中检索数据,并将其存储本身,但我要处理的组件内的数据。我不能工作,如何有分量执行功能的服务已检索和存储数据本身之后。

service.ts

import { Injectable } from 'angular2/core';    
import { Http } from 'angular2/router';

@Injectable()
export class Service {
    result: Object;

    constructor(http: Http) {
        this.http = http;
    }

    httpGet(url) {
        return this.http.get(url).subscribe(
            result => this.result = result.json(),
            error => console.log(error),
            () => {}
        )
    }
}

component.ts

import { Component } from 'angular2/core';
import { Service } from './service';

@Component({
    ...
})
export class Component {
    formattedResult: Object;

    constructor(service: Service) {
        this.service = service;
        this.service.httpGet('/api')

        // How do I call format result on service.result only after it is completed?
        this.formatResult(service.result) // Need to execute this after the http call is completed

        // I want something like:
        this.service.httpGet('/api').then(() => formatResult(this.service.result));
    }

    formatResult(result) {
        this.formattedResult = result.map(x => x.length) // For example
    }
}
angular asynchronous rxjs observable
4个回答
5
投票

要回答我的问题:

在应用程序根目录,进口Rxjs有:

import 'rxjs/Rx';

这使您可以访问完整的可观察对象(不只是“可观察-精简版”包含角)。这使您可以.MAP。降低等HTTP请求。

您现在可以使用.MAP在HTTP请求中的服务的情况下,进行任意代码,即使是赞成的结果的组件。因此,要达到什么样的我阐述了在开始的时候,我们可以做的:

service.ts

import { Injectable } from 'angular2/core';    
import { Http } from 'angular2/router';

@Injectable()
export class Service {
    result: Object;

    constructor(http: Http) {
        this.http = http;
    }

    httpGet(url) {
        return this.http.get(url).map(
            result => {
                let data = result.json();
                this.result = data;
                return data
            }
        )
    }
}

component.ts

import { Component } from 'angular2/core';
import { Service } from './service';

@Component({
    // Component setup
})
export class Component {
    formattedResult: Object;

    constructor(service: Service) {
        this.service = service;
        this.service.httpGet('/api').subscribe(
            data => this.formatResult(data);
        );
    }

    formatResult(result) {
        this.formattedResult = result.map(x => x.length) // For example
    }
}

由于冈特和马克的答复,帮我满脑子都在这一点,我觉得我的理解观测量好得多已经通过大量的文档解决这个问题了!


2
投票

检查结果已经到达,如果是,创建一个新的承诺,并用结果完成它,而不是没有,把它拿来,并返回它的承诺为好。

@Injectable()
export class Service {
    result: Object;

    constructor(http: Http) {
        this.http = http;
    }

    httpGet(url) {
        if(result === undefined) {
          return this.http.get(url).toPromise().then(
              result => this.result = result.json(),
              error => console.log(error);
          );
        } else {
          return new Promise().resolve(result);
        }
    }
}

我不知道TS这个代码可能包含一些错误(我用的角度仅DART),但你应该明白我的意思。

也可以看看 - http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html


0
投票

那么你可以使用一个回调函数在这种情况下,

以例如,考虑这是后函数触发后服务业务模块

postData(id: string, name: string) {
    console.log("Got you",id);
  this._employeeService.postServices({id: id, name: name})
    .subscribe(
      (response:Response) => this.consoleMyOutput(),
      error => console.log(error)
    );  
}

这里要注意的功能consoleMyOutput()。一旦响应了该服务已被调用后,这将触发

现在,

consoleMyOutput(){console.log("Write Your call back function")};

该功能只会之后被触发。


0
投票

它可以与Rxjs方法简单一点,这里是简单而经典的方式来调用服务一次,然后加载应用程序后,我们可以订阅它分成多个组成部分。确保服务应是可重复使用的所有组件,所以做多为u可以做服务和地图代码,只有在认购组件:

服务:

 import { Injectable } from 'angular2/core';    
 import { Http } from 'angular2/http';

 @Injectable()
 export class Service {
     result: Object;

     constructor(private http: Http) {}

     private _urlGet = '/api';

     httpGet(){
        return this.http.get(this._urlGet)
          .map(res => JSON.parse(res.json()))
          .do(result => {
             this.result = result;
           }, error => console.log(error))
     }
  }

零件

 export class Component {
    formattedResult: Object;

    constructor(private service: Service) { }

    ngOnInit(){
       this.service.httpGet().subscribe(result => {
          this.formattedResult = result;
       }
    }
 }
© www.soinside.com 2019 - 2024. All rights reserved.