Angular ort let CountryProvider={Provider:'CountryFactory', useFactory:(httpService)=>{ 返回(值)=>{ 返回新国家/地区(值,httpService) }; }, 副部长:[Http
ort let CountryProvider={Provider:'CountryFactory', useFactory:(httpService)=>{ 返回(值)=>{ 返回新国家/地区(值,httpService) }; }, 副部长:[HttpService] } @NGD模块({ 导入:[浏览器模块,HttpModule], 声明:[App], 引导:[应用程序], 供应商:[ HttpService, 乡村提供者 ] }) 导出类AppModule{}Angular ort let CountryProvider={Provider:'CountryFactory', useFactory:(httpService)=>{ 返回(值)=>{ 返回新国家/地区(值,httpService) }; }, 副部长:[Http,angular,typescript,dependency-injection,Angular,Typescript,Dependency Injection,ort let CountryProvider={Provider:'CountryFactory', useFactory:(httpService)=>{ 返回(值)=>{ 返回新国家/地区(值,httpService) }; }, 副部长:[HttpService] } @NGD模块({ 导入:[浏览器模块,HttpModule], 声明:[App], 引导:[应用程序], 供应商:[ HttpService, 乡村提供者 ] }) 导出类AppModule{} 谢谢您的回答。我有几个问题
谢谢您的回答。我有几个问题。我假设提供者块(第一个和第三个代码块)将进入我的应用程序提供者数组?在provider块中,行“newtestmodel(http,config),deps:[http,config];”出现错误时,我将“deps”属性移动到use factory下面,使其成为provider对象的属性根级别。现在,当我使用代码时,我得到了这个。testModelFactory不是一个函数,应该将代码添加到提供者数组
引导(AppComponent,[OtherProvider,{provider:…}])
或@组件(…提供者:[{provider:…}])
deps
只是一个示例依赖项,您可以根据实际需求删除或替换它(需要传递给服务构造函数的内容9让它工作起来了!我必须做一些更改,在provider对象中,deps必须在对象的根级别,而不是在内部函数中。这两个函数都需要返回。因此外部函数、useFactory函数需要返回内部函数和内部函数n需要返回新型号。抱歉,你是对的,我错过了(目前也只是在电话中)很高兴听到你找到了答案。我编辑了你的代码,使之符合我的要求。再次感谢你的帮助!你应该将此作为对帖子的编辑或对所选答案的评论,以便发现此问题的人可以看到。
import { Component, OnInit } from '@angular/core';
import { TestService } from './shared/test.service';
import { TestModel } from './shared/test.model';
import { TestDetailComponent } from './test-detail.component';
@Component({
selector: "test-component",
templateUrl: 'app/test/test.component.html',
styleUrls: [],
providers: [TestService],
directives: [TestDetailComponent]
})
export class TestComponent implements OnInit {
tests: TestModel[] = [];
selectedTest: TestModel;
constructor(private testService: TestService) {};
ngOnInit() {
this.testService.getTestsModels().subscribe( (tests) => {
console.log(tests);
this.tests = tests
});
}
}
<select [(ngModel)]="selectedTest">
<option *ngFor="let test of tests" [ngValue]="test">{{test.testing}}</option>
</select>
<test-detail *ngIf="selectedTest" [test]="selectedTest"></test-detail>
import { Component, Input } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { TestModel } from './shared/test.model';
@Component({
selector: 'test-detail',
templateUrl: 'app/test/test-detail.component.html',
pipes: [JsonPipe]
})
export class TestDetailComponent {
@Input() test;
}
<p style="font-size: 3em;">{{test | json}}</p>
import { Injectable, Inject } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { CONFIG } from './../../config/constants';
@Injectable()
export class TestModel {
"testing": number;
"that": string;
"a": string;
constructor(private http: Http, @Inject(CONFIG) private config) {}
save(): Observable<TestModel[]> {
let url = this.config.apiUrl + "test";
let body = JSON.stringify({
testing: this.testing,
this: this.that,
a: this.a
});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(url, body, options)
.map( (response) => response.json() )
.map( (results) => {
results.map( (aggregate, current) => {
aggregate.push(<TestModel>current);
return aggregate;
}, new Array<TestModel>())
}).catch(this.handleError);
}
update() {
let url = this.config.apiUrl + "test";
let body = JSON.stringify({
testing: this.testing,
this: this.that,
a: this.a
});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.put(url, body, options)
.map( (response) => response.json() )
.map( (results) => {
results.map( (aggregate, current) => {
aggregate.push(<TestModel>current);
return aggregate;
}, new Array<TestModel>())
}).catch(this.handleError);
}
private handleError(err): Observable<any> {
let errMessage = err.message ? err.message : err.status ? `${err.status} - ${err.statusText}` : 'Server Error';
return Observable.throw(new Error(errMessage));
}
}
import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { CONFIG } from './../../config/constants';
import { TestModel } from './test.model';
@Injectable()
export class TestService {
constructor(private http: Http, @Inject(CONFIG) private config) {}
getTestsModels(): Observable<TestModel[]> {
let url = this.config.apiUrl + "test";
return this.http.get(url)
.map( (response) => response.json() )
.map( (results) => {
return results.map( (current) => {
return <TestModel>current; // <<<--- here is the error
})
})
.catch(this.handleError);
}
private handleError(err): Observable<any> {
let errMessage = err.message ? err.message : err.status ? `${err.status} - ${err.statusText}` : 'Server Error';
return Observable.throw(new Error(errMessage));
}
}
import { Injectable, Inject, ReflectiveInjector } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { CONFIG } from './../../config/constants';
import { TestModel } from './test.model';
@Injectable()
export class TestService {
constructor(private http: Http, @Inject(CONFIG) private config) {}
getTestsModels(): Observable<TestModel[]> {
let url = this.config.apiUrl + "test";
return this.http.get(url)
.map( (response) => response.json() )
.map( (results) => {
return results.map( (current) => {
return ReflectiveInjector.resolveAndCreate([TestModel]).get(TestModel);
})
})
.catch(this.handleError);
}
private handleError(err): Observable<any> {
let errMessage = err.message ? err.message : err.status ? `${err.status} - ${err.statusText}` : 'Server Error';
return Observable.throw(new Error(errMessage));
}
}
{
provide: 'TestModelFactory',
useFactory: () => {
return (http, config) => {
return new TestModel(http, config);
};
},
deps: [Http, CONFIG];
}
@Injectable()
export class TestService {
constructor(@Inject('TestModelFactory' testModelFactory) {}
getTestsModels(): Observable<TestModel[]> {
let url = this.config.apiUrl + "test";
return this.http.get(url)
.map( (response) => response.json() )
.map( (results) => {
return results.map( (current) => {
let tm = testModelFactory();
tm.xxx // assign data
})
})
.catch(this.handleError);
}
}
{
provide: 'TestModelFactory',
useFactory: (json) => {
return (http, config) => {
return new TestModel(http, config, json);
};
},
deps: [Http, CONFIG];
}
@Injectable()
export class TestService {
constructor(@Inject('TestModelFactory' testModelFactory) {}
getTestsModels(): Observable<TestModel[]> {
let url = this.config.apiUrl + "test";
return this.http.get(url)
.map( (response) => response.json() )
.map( (results) => {
return results.map( (current) => {
let tm = testModelFactory(result);
})
})
.catch(this.handleError);
}
}
@Injectable()
export class TestService {
constructor(private http: Http, @Inject(CONFIG) private config) {}
getTestsModels(): Observable<TestModel[]> {
let url = this.config.apiUrl + "test";
return this.http.get(url)
.map( (response) => response.json() )
.map( (results) => {
return results.map( (current) => {
return new TestModel(http, config);
})
})
.catch(this.handleError);
}
private handleError(err): Observable<any> {
let errMessage = err.message ? err.message : err.status ? `${err.status} - ${err.statusText}` : 'Server Error';
return Observable.throw(new Error(errMessage));
}
}
import {Component, NgModule, VERSION, Injectable, Inject} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {HttpClient} from '@angular/common/http'
import {HttpModule} from '@angular/http'
@Injectable()
export class HttpService{
token = 'hihaa';
constructor(){
}
myFunction(value){
console.log(value)
}
}
export class Country{
constructor(value,public httpService: HttpService){
console.log(value,this);
}
classes(){
this.httpService.myFunction('BGGGG')
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
country:any;
constructor(
@Inject('CountryFactory') countryFactory
) {
this.name = `Angular! v${VERSION.full}`;
this.country = countryFactory(3);
this.country.classes();
}
}
export let CountryProvider = { provide: 'CountryFactory',
useFactory: (httpService) => {
return (value) =>{
return new Country(value,httpService)
};
},
deps: [HttpService]
}
@NgModule({
imports: [ BrowserModule,HttpModule ],
declarations: [ App ],
bootstrap: [ App ],
providers: [
HttpService,
CountryProvider
]
})
export class AppModule {}