我想调用 HomePage 类中存在的函数,该函数位于我想要使用该函数的(类 Popover)之外,我已经做了一些研究,我想我需要做一些类似依赖注入(inject)的事情,我尝试遵循一些教程,但我不够幸运地解决了这个问题。
弹出框类:
@Component({
template: `
<div>
<button ion-item *ngFor="let city of cities" (click)="switchToThisCity(city.cityName);close();">{{city.cityName | uppercase}}</button>
</div>
`
})
class MyPopover{
static get parameters(){
return [[Http], [ViewController]];
}
constructor(http, viewCtrl) {
this.http = http;
this.viewCtrl = viewCtrl;
//Async Call
var getCities = new URLSearchParams();
this.http.get('https://restApi.com/class/outlet', {headers: ParseHeaders}).subscribe(data => {
this.cities = data.json().results;
});
///
}
close() {
this.viewCtrl.dismiss();
}
switchToThisCity(currentCity){
//I WANT TO CALL THIS FUNCTION WHICH EXISTS ON HomePage CLASS
return getQueries(currentCity);
}
}
主页类:
@Component({
templateUrl: 'build/pages/home/home.html',
})
export class HomePage {
static get parameters(){
return [[NavController],[Http], [NavParams]];
}
// this.cartLength = this.cart.items.length;
constructor() {}
//I NEED TO USE THIS IN THE POPOVER CLASS
getQueries(city){
var cities = new URLSearchParams();
cities.set('cityName', city);
this.http.get('https://restApi.com/classes/citiesList', { search : dishesParams, headers: ParseHeaders}).subscribe(data => {
this.getCities = data.json().results;
});
}
}
最佳答案
创建服务类
cities.service
@Injectable()
export class CitiesService {
getQueries(city) {
var cities = new URLSearchParams();
cities.set('cityName', city);
return this.http.get('https://restApi.com/classes/citiesList', {
search: dishesParams,
headers: ParseHeaders
}) // here we return an observable so we can subscribe to it in our class
}
在 Popover 中:(与主页类相同)
export class MyPopover{
constructor(private citiesService:CitiesService) {
}
// and this is how you use the function
this.citiesService.getQueries().subscribe(data => {
this.getCities = data.json().results;
});
}
更新:看看这篇文章:http://nicholasjohnson.com/blog/how-to-do-everything-in-angular2-using-es6/
First up, anything is injectable in Angular, so PetService can be just a newable function.
The Angular DI mechanism will automatically use it to create a singleton that is local to the correct branch of the injector tree. If you only have a root injector (made automatically by Angular 2 on bootstrap), this will be a global singleton, just like Angular
这里的原理是创建一个处理请求的服务并注入(inject)它,返回一个可观察的对象并订阅,然后你可以对响应做任何你想做的事情......
关于javascript - Angular 2 - 调用当前类外部存在的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38897188/