我正在尝试通过useFactory
组件文件
..other deps..
import { SearchService } from './search.service';
import { Http } from '@angular/http';
export function myServiceFactory(http) {
return SearchService.getItem(http);
// I need this to return '12345'
}
@Component({
selector: 'my-test',
templateUrl: './my-test.html',
providers: [
{
provide: "myTestService",
deps: [Http],
useFactory: myServiceFactory
}
]
})
搜索服务文件
import {Injectable} from '@angular/core';
import {Http, Request, RequestMethod, Response} from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class SearchService {
static getItem(http) {
const request = new Request({
'method': RequestMethod.Get,
'url': 'my-url/search'
});
http.request(request).subscribe((data) => {
return data.itemKey; // data.itemKey = '12345' in this case
});
}
}
基本上我需要12345
通过myServiceFactory
为我的'myTestService
'提供商。
有办法做到这一点吗?非常感谢!
答案 0 :(得分:0)
尝试InjectionToken:
..other deps..
import { InjectionToken, OnInit } from '@angular/core';
import { SearchService } from './search.service';
import { Http } from '@angular/http';
export const VALUES_TOKEN = new InjectionToken<string>('my items');
export function myServiceFactory(http) {
return SearchService.getItem(http);
// I need this to return '12345'
}
@Component({
selector: 'my-test',
template: `
<h3>My Values</h3>
{{allValues}}
`,
providers: [
{
provide: VALUES_TOKEN,
deps: [Http],
useFactory: myServiceFactory
}
]
})
export class MyComponent implements OnInit {
constructor(@Inject(VALUES_TOKEN) private allValues: string) { }
ngOnInit() {
}
}