Javascript 如何在Ng2智能表中创建、编辑和删除数据
我在angular 2项目中使用了[ng2 smart table],我需要使用http.post()方法发送一个API请求,但当我在控制台中单击按钮确认数据时出现了此错误: 错误类型错误:_co.addClient不是函数 这是服务中的代码。ts:Javascript 如何在Ng2智能表中创建、编辑和删除数据,javascript,angular,typescript,ng2-smart-table,Javascript,Angular,Typescript,Ng2 Smart Table,我在angular 2项目中使用了[ng2 smart table],我需要使用http.post()方法发送一个API请求,但当我在控制台中单击按钮确认数据时出现了此错误: 错误类型错误:_co.addClient不是函数 这是服务中的代码。ts: import { Injectable } from '@angular/core'; import { Clients } from './clients.model'; import { HttpClient, HttpErrorRespons
import { Injectable } from '@angular/core';
import { Clients } from './clients.model';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ClientsService {
url="http://localhost:21063/api/clints"
clients:Clients[];
client:Clients;
constructor(private http:HttpClient) { }
getAllClients(): Observable<Clients[]>{
return this.http.get<Clients[]>(this.url);
}
addClient(event){
this.http.post<Clients>(this.url,this.client)
.subscribe(
res=>{
console.log(res);
event.confirm.resolve(event.Clients);
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("Client-side error occurred.");
} else {
console.log("Server-side error occurred.");
}
}
)
}
<div class="mainTbl">
<ng2-smart-table
[settings]="settMain"
[source]="this.Service.clients"
(createConfirm)="addClient($event)"
(editConfirm)="onEditConfirm($event)"
(deleteConfirm)="onDeleteConfirm($event)"
></ng2-smart-table>
</div>
那么我怎样才能找到我的错误呢?处理创建、编辑和删除操作的最佳方法是什么?
提前感谢这是因为
addClient
是service.ts
上的一个方法,而ng2智能表
是在该组件上实例化的,您不应该直接在模板上调用您的服务方法
因此,正确的做法是在component.ts上创建一个调用addClient
方法的方法
在component.html模板上,我们将editConfirm
事件绑定到另一个方法onAddClient
<div class="mainTbl">
<ng2-smart-table
[settings]="settMain"
[source]="this.Service.clients"
(createConfirm)="onAddClient($event)"
(editConfirm)="onEditConfirm($event)"
(deleteConfirm)="onDeleteConfirm($event)"
></ng2-smart-table>
</div>
此外,在service.ts上,您将从compnoent传递数据,并从http客户端返回http请求的响应
addClient(data){
console.log(data);
return this.http.post<Clients>(this.url, data);
}
addClient(数据){
控制台日志(数据);
返回this.http.post(this.url,data);
}
非常感谢您的支持和说明,在我按照您提到的那样做之后,我遇到了另一个错误类型错误:将循环结构转换为JSON-->从具有构造函数“Subscriber”|属性“u subscriptions”->具有构造函数“Array”的对象|索引0->具有构造函数的对象SubjectSubscription
我想这是因为数据需要转换为json,但我不知道如何转换,你能帮助@wentjunah我明白了。。等等,但是数据不是对象或数组格式吗?这应该是有效的JSON
onAddClient(event) {
this.Service.addClient(event).subscribe(
(res) => {
// handle success
}, (error) => {
// handle error
});
}
addClient(data){
console.log(data);
return this.http.post<Clients>(this.url, data);
}