我在几分钟内创建了一些非常基本和快速的东西,因此很容易重现。
我创建了一个应用程序,使用:
ionic start blank --v2然后我创建了一个提供程序:
ionic g provider FacebookFriends然后,我将此代码放入我的提供程序中:
import {Injectable, Inject} from 'angular2/core';
import {Http} from 'angular2/http';
/*
Generated class for the FacebookFriends provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class FacebookFriends {
constructor(@Inject(Http) http) {
this.http = http;
this.data = null;
}
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.get('path/to/data.json')
.map(res => res.json())
.subscribe(data => {
// we've got back the raw data, now generate the core schedule data
// and save the data for later reference
this.data = data;
resolve(this.data);
});
});
}
}然后我尝试将其注入到app.js中:
import {App, Platform} from 'ionic-angular';
import {TabsPage} from './pages/tabs/tabs';
import {FacebookFriends} from './providers/facebook-friends/facebook-friends';
@App({
template: '<ion-nav [root]="rootPage"></ion-nav>',
config: {}, // http://ionicframework.com/docs/v2/api/config/Config/,
providers: [FacebookFriends]
})
export class MyApp {
static get parameters() {
return [[Platform]];
}
constructor(platform, private _facebookFriends) {
this.rootPage = TabsPage;
platform.ready().then(() => {
});
}
}这就是我所做的。当我运行ionic serve时,我得到了很多错误。我知道有一个未知的标记,它指向@Inject和@Injectable这两个单词。我还在private _facebookFriends行得到了一个意想不到的标记。
另外,如果我尝试在构造函数中添加一个类型,这样就会有platform:Platform和_facebookFriends:FacebookFriends,我也会发现':‘是未知的标记。
我本质上只是尝试从我的app.js调用一个服务,但它不工作。
发布于 2016-03-21 14:09:29
默认情况下,Ionic中提供Http。向构造函数添加一个参数就足够了:
import {Http} from 'angular2/http';
@Injectable
export class FacebookFriends{
constructor(private http:Http){}
}发布于 2016-03-21 16:48:56
我认为您需要在parameters getter中添加FacebookFriends:
export class MyApp {
static get parameters() {
return [[Platform, FacebookFriends]];
}
(...)
}getter返回的数组需要与构造函数中预期的所有参数相匹配。如果有两个参数,则数组中需要两个参数。在providers属性中定义服务仅指定可以注入此服务。要真正注入它,您需要在parameters getter中定义它。
您还需要为服务定义一个parameters getter:
@Injectable()
export class FacebookFriends {
static get parameters() {
return [[Http]];
}
constructor(http) {
this.http = http;
this.data = null;
}
(...)
}您可以注意到,使用ES6时,不可能在构造函数参数级别使用@Inject ...
https://stackoverflow.com/questions/36121109
复制相似问题