0

如果我有一个看起来像这样的服务

import {Injectable} from 'angular2/core';

@Injectable()
export class MyService {

  search(oSrchParams){

    let promise = () =>
    new Promise((resolve, reject) =>
      Meteor.call('mockSearchWS', (error:any, result:any) => error ? reject(error) : resolve(result))
    );

    promise().then(
      (result:Array<Object>) => {
        return result
      },
      (error) => {
        console.log('failed', error);
      }
    )
  }
}

注入时如何调用它并获取值?像这样:

import {Component} from 'angular2/core';
import {MyService} from './my-service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Component ({
  selector: 'search',
  providers:[MyService]
})

export class App {
  items: Array<string>;
  constructor(private myService: MyService) {
 }

 search(term) {
    // this.myService.search(term).then(items => this.items = items);
    // this.myService.search(term).subscribe()
  }
}

我不确定该服务是否是可观察的。我见过的大多数示例都使用 http。

4

2 回答 2

0

对于任何在这里找到路的人来说,只有几件事。我为该方法添加了一个类型

search(oSrchParams): any { ...}

电话变成了

this._searchCall.search(oSrchParams).then(
  (item) => (
    this._ngZone.run(()=>{
      this.items = result,
      (console.log("search", JSON.stringify(this.items)))
    })
  )
);

ngZone 像服务一样被注入到构造函数中,并确保对的更改this.items反映在浏览器中。我可能有太多(),但它有效:-)

于 2016-03-06T09:05:01.170 回答
0

您必须在搜索方法中返回承诺:

  search(oSrchParams){

    let promise = () =>
    new Promise((resolve, reject) =>
      Meteor.call('mockSearchWS', (error:any, result:any) => error ? reject(error) : resolve(result))
    );

    return promise().then(
      (result:Array<Object>) => {
        return result
      },
      (error) => {
        console.log('failed', error);
      }
    )
  }
}

这样您就可以在调用此方法的组件中调用 then :

 search(term) {
    this.myService.search(term).then(items => this.items = items);
}
于 2016-03-06T07:18:45.103 回答