我正在玩Aurelia介绍教程并更改它以从自定义类进行休息调用。在我的班级中,我的方法调用出现'http is undefined'错误,因此看来Aurelia服务没有被注入。如果Aurelia没有加载类模块,是否会注入工作?
home.js:
<customErrors mode="On" defaultRedirect="Error">
<error statusCode="404" redirect="~/Error/Error404" />
</customErrors>
search.js:
import 'bootstrap/css/bootstrap.min.css!';
import 'bootstrap/css/bootstrap-theme.min.css!';
import 'styles/style.css!'
import 'bootstrap';
import {Search} from '../lib/search.js';
export class Home {
heading = 'Welcome to Aurelia!';
firstName = 'John';
lastName = 'Doe';
activate() {
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
submit() {
var s = new Search();
s.fetch()
.then(results => this.results = results);
}
}
错误:
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';
@inject(HttpClient)
export class Search {
constructor(http) {
// constructor is called but http is undefined
http.configure(config => {
config
.useStandardConfiguration();
});
this.http = http;
}
fetch() {
// ERROR OCCURS HERE
return this.http.fetch('find')
.then(response => response.json());
}
}
答案 0 :(得分:2)
Search
必须在Home
中注入,最好不要在导入时使用.js
import {Search} from '../lib/search';
@inject(Search)
export class Home {
constructor(search) {
}
}
UPD:这里https://stackoverflow.com/a/34796010/3436921你可以找到更多关于使用注射的不同方法的例子
UPD2:或者您可以手动将HttpClient
实例传递给Search
构造函数
import {HttpClient} from 'aurelia-fetch-client';
@inject(HttpClient)
export class Home {
constructor(http) {
this.http = http;
}
...
submit() {
var s = new Search(this.http);
...
}
}