下面是我的saveComponent代码。我的所有要求都没有正常工作。当我发布帖子请求时,我得到了#34;无法读取属性' post'未定义"
SaveComponent.ts
import {Component, OnInit} from '@angular/core';
import {Liv} from '../../services/models/liv.model';
import {Livre} from '../../services/models/livre.model';
import {ActivatedRoute, Router} from "@angular/router";
declare var require: any;
@Component({
selector: 'app-save',
templateUrl: './save.component.html',
styleUrls: ['./save.component.css']
})
export class SaveComponent implements OnInit {
prod = new Liv() ;
test = require('../../services/index');
constructor(public router: Router, public activatedRoute: ActivatedRoute) {
}
ngOnInit() {
}
saveProduit() {
console.log(this.test.ApiClientService.prototype.sendRequest)
this.prod.id = null;
this.test.ApiClientService.prototype.save(this.prod)
.subscribe(data => {
console.log("this is" + data);
alert("ID:" + this.prod.nom);
this.router.navigate(['show-all']);
}, err => {
console.log(err);
});
}}
../../服务/ index.ts
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import {
Livre
} from './models';
/**
* Created with angular4-swagger-client-generator.
*/
@Injectable()
export class ApiClientService {
private domain = 'http://localhost:8084';
constructor(private http: HttpClient, @Optional() @Inject('domain') domain: string ) {
if (domain) {
this.domain = domain;
}
}
public save(body: Livre): Observable<HttpResponse<any>> {
let uri = `/Livre/add`;
let headers = new HttpHeaders();
let params = new HttpParams();
return this.sendRequest<any>('post', uri, headers, params, JSON.stringify(body));
}
private sendRequest<T>(method: string, uri: string, headers: HttpHeaders, params: HttpParams, body: any): Observable<HttpResponse<T>> {
if (method === 'post') {
return this.http.post<T>(this.domain + uri, body, { headers: headers.set('Content-Type', 'application/json'), params: params, observe: 'response' });
} else {
console.error('Unsupported request: ' + method);
return Observable.throw('Unsupported request: ' + method);
}
}
}
saveComponent.html
<div class="container spacer">
<div class="panel panel-primary">
<div class="panel-heading">Nouveau Livre:</div>
<div class="panel-body">
<div class="form-group">
<label class="control-label">Nom:</label>
<input class="form-control" type="text" [(ngModel)]="prod.nom"/>
</div>
<div class="form-group">
<label class="control-label">auteur:</label>
<input class="form-control" type="text" [(ngModel)]="prod.auteur"/>
</div>
<div class="form-group">
<label class="control-label">prix:</label>
<input class="form-control" type="text" [(ngModel)]="prod.prix"/>
</div>
<button class="btn btn-primary" (click)="saveProduit()">Save</button>
</div>
</div>
</div>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import {ApiClientService} from '../services/index'
import { AppComponent } from './app.component';
import { SaveComponent } from './save/save.component';
import {RouterModule, Routes} from "@angular/router";
import {HttpModule} from "@angular/http";
import {FormsModule} from "@angular/forms";
import { DeleteComponent } from './delete/delete.component';
import { UpdateComponent } from './update/update.component';
import { SearchComponent } from './search/search.component';
import { ShowAllComponent } from './show-all/show-all.component';
const appRoutes:Routes=[
{path:'new-produit',component:SaveComponent},
{path:'delete-produit',component:DeleteComponent},
{path:'update-produit',component:UpdateComponent},
{path:'search-produit',component:SearchComponent},
{path:'show-all',component:ShowAllComponent},
{path:'',redirectTo:'/show-all', pathMatch:'full'}
]
@NgModule({
declarations: [
AppComponent,
SaveComponent,
DeleteComponent,
UpdateComponent,
SearchComponent,
ShowAllComponent
],
imports: [
BrowserModule , HttpClientModule, RouterModule.forRoot(appRoutes), HttpModule, FormsModule
],
providers: [ApiClientService],
bootstrap: [AppComponent]
})
export class AppModule { }
错误
SaveComponent.html:19 ERROR TypeError: Cannot read property 'post' of undefined
at Object.ApiClientService.sendRequest (index.ts:90)
at Object.ApiClientService.save (index.ts:32)
at SaveComponent.saveProduit (save.component.ts:35)
at Object.eval [as handleEvent] (SaveComponent.html:19)
at handleEvent (core.js:13589)
at callWithDebugContext (core.js:15098)
at Object.debugHandleEvent [as handleEvent] (core.js:14685)
at dispatchEvent (core.js:10004)
at eval (core.js:10629)
at HTMLButtonElement.eval (platform-browser.js:2628)
我尝试使用函数require导入服务但是de http未在de ts文件中注入
答案 0 :(得分:0)
这是使用依赖注入的正确方法。您不应该使用您正在使用的原型方法,因为它不会正确地实例化该类。
要使服务可用于依赖项注入,您需要将其添加到模块的provides
列表中。您可能希望阅读依赖注入here
<强> SaveComponent.ts 强>
import {Component, OnInit} from '@angular/core';
import {Liv} from '../../services/models/liv.model';
import {Livre} from '../../services/models/livre.model';
import {ApiClientService} from '../../services/index';
import {ActivatedRoute, Router} from "@angular/router";
// ...
@Component({
selector: 'app-save',
templateUrl: './save.component.html',
styleUrls: ['./save.component.css']
})
export class SaveComponent implements OnInit {
// ...
constructor(
public router: Router,
public activatedRoute: ActivatedRoute,
private apiClientService: ApiClientService
) {}
// ...
saveProduit() {
this.prod.id = null;
this.apiClientService.save(this.prod);
// ...