在我的情况下如何从http请求返回数据?

时间:2017-12-01 00:32:06

标签: angular typescript

我正在尝试通过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'提供商。

有办法做到这一点吗?非常感谢!

1 个答案:

答案 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() {
    }
}