如果我的服务看起来像这样
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。
答案 0 :(得分: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);
}
答案 1 :(得分: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
的更改反映在浏览器中。我可能有太多(),但它有效: - )