我正在研究这个项目,同时学习角度知识。
我有一个交易表(与餐馆有关),然后单击“保存”按钮,它将数据发送到数据库。很好。
我有一个名为DealModel的模型,我有一个AddDeal组件,我在这里要做的是从该组件发送表单值而不是使用服务,因此我很困惑的是如何发送首先确定服务的价值(从服务到数据库是微不足道的,因为它已经实现)
这里是看功能 PS:我相信我应该保持现状,但是我想团队需要维护服务
enregistrerDeal() {
//sorry some of it in French.
//these are just form values.
this.Restaurant = new Etablissement();
this.Restaurant.id=this.selectedValue;
const deal:Deal = {
titre: this.dealForm.controls['titre'].value,
dateD : this.dealForm.controls['dateD'].value,
dateF :this.dealForm.controls['dateF'].value,
descriptif: this.dealForm.controls['descriptif'].value,
//images:this.dealForm.controls['images'].value,
prixActuel: this.dealForm.controls['prixActuel'].value,
nombreDeals:this.dealForm.controls['nombreDeals'].value,
etablissement: this.Restaurant, //this.dealForm.controls['etablissement'].value,
disponibilite: this.dealForm.controls['disponibilite'].value,
}
this.notif.messege = 'gerant ' + this.Restaurant.id + ' a ajoute un deal à' + this.EtablissementsByGerant.nom;
//console.log("la valeur est"+this.dealForm.controls['etablissement'].value);
//here it does send it to spring?
this.http.post(this.apiUrls.addDeal, deal ,
{
headers: new HttpHeaders()
.set("Content-Type", "application/json")
}
)
.subscribe(
data => {
//console.log(deal);
//console.log("la valeur du resteau ajoutée est"+this.dealForm.controls['etablissement'].value);
// window.location.reload();
this.toastr.success('votre deal a ete ajouter ');
this.http.get('http://localhost:8081/api/notify/' + this.notif.messege, {
headers: new HttpHeaders()
.set("Content-Type", "application/json")
})
.subscribe(
(data: any) => {
console.log('notif envoye');
}
)
this.router.navigate(['displayDeals']);
// console.log(deal);
} );
//console.log(deal);
}
}
答案 0 :(得分:1)
创建一个实现DealService
功能的addDeal
。
服务应处理您应用程序中的逻辑。 (在这种情况下,可以达成协议并将其放入服务器中)
使用angualr cli创建DealSerivece:ng generate service Deal
并将addDeal函数添加到服务
结果:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class DealService {
constructor() { }
addDeal(deal:Deal) {
// here you need to do the post request to server (exactly as you did in the component just move it to here).
// you can return an observable and subscribe in the component if you like
}
}
将Dealservice
导入并注入到您的组件中,并使用服务中的addDeal
函数:
// deal.component.ts
import { Dealservice } from '../deal.service';
// just add the Dealservice
constructor(private dealService: Dealservice ) { }
// now use the service in the right place:
enregistrerDeal(){
....
....
...
const deal:Deal = { ... }
this.dealService.addDeal(deal)
// you can subscribe if you like to..
}
在app.module.ts
中,您需要将服务添加到providers数组
import { DealService } from './deal.service';
providers : [DealService]
其基于有角度的文档: Service docs