Angular 更新角度传感器中的CRUD组件,但不保存数据
这是我的更新组件:Angular 更新角度传感器中的CRUD组件,但不保存数据,angular,typescript,json-server,Angular,Typescript,Json Server,这是我的更新组件: import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-update-person', templateUrl: './update-person.c
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-update-person',
templateUrl: './update-person.component.html',
styleUrls: ['./update-person.component.css']
})
export class UpdatePersonComponent implements OnInit {
id: number;
data: object = {};
// person = []; //ERROR TypeError: Cannot read property 'length' of undefined
// person = any; //ERROR Error: Uncaught (in promise): ReferenceError: any is not defined
person: any; //ERROR TypeError: Cannot read property 'length' of undefined
exist = false;
personObj: object = {};
private headers = new Headers({ 'Content-Type': 'application/json' });
constructor(
private router: Router,
private route: ActivatedRoute,
private http: HttpClient
) {}
confirmationString: string = 'Person updated successfully !!';
isUpdated: boolean = false;
updatePerson = function(person) {
this.personObj = {
p_id: person.p_id,
p_username: person.p_username,
p_image: person.p_image
};
const url = `${'http://localhost:5555/person'}/${this.id}`;
this.http
.put(url, JSON.stringify(this.personObj), { headers: this.headers })
.toPromise()
.then(() => {
this.router.navigate(['/']);
});
};
ngOnInit() {
this.route.params.subscribe(params => {
this.id = +params['id'];
});
this.http
.get('http://localhost:5555/person')
.subscribe((res: Response) => {
this.isUpdated = true;
this.person = res;
for (var i = 0; i < this.person.length; i++) {
if (parseInt(this.person[i].id) === this.id) {
this.exist = true;
this.data = this.person[i];
break;
} else {
this.exist = false;
}
}
});
}
}
从'@angular/core'导入{Component,OnInit};
从'@angular/Router'导入{Router,ActivatedRoute};
从'@angular/common/http'导入{HttpClient};
@组成部分({
选择器:“应用程序更新人员”,
templateUrl:'./更新person.component.html',
样式URL:['./更新person.component.css']
})
导出类UpdatePersonComponent实现OnInit{
id:编号;
数据:对象={};
//person=[];//错误类型错误:无法读取未定义的属性“length”
//person=any;//错误:未捕获(承诺中):ReferenceError:any未定义
person:any;//错误类型错误:无法读取未定义的属性“length”
存在=错误;
personObj:object={};
私有头=新头({'Content-Type':'application/json'});
建造师(
专用路由器:路由器,
专用路由:激活的路由,
私有http:HttpClient
) {}
confirmationString:string='Person updated successfully!!';
isUpdated:boolean=false;
updatePerson=功能(个人){
this.personObj={
p_id:person.p_id,
p_用户名:person.p_用户名,
p_image:person.p_image
};
常量url=`${'http://localhost:5555/person'}/${this.id}`;
这是http
.put(url,JSON.stringify(this.personObj),{headers:this.headers})
.toPromise()
.然后(()=>{
this.router.navigate(['/']);
});
};
恩戈尼尼特(){
this.route.params.subscribe(params=>{
this.id=+params['id'];
});
这是http
.get('http://localhost:5555/person')
.订阅((回复)=>{
this.isUpdated=true;
this.person=res;
for(var i=0;i
这样做不会抛出任何错误。但是,单击“更新”按钮后,空白数据将保存到我的json服务器
认为问题在于
人:任何代码>。您可以看到我用person变量尝试过的其他一些事情以及我得到的相应错误。通常建议您将数据访问代码放入服务中,而不是组件中
我通常使用post创建新数据,并使用put更新现有数据
我的更新方法(在我的数据访问服务中)如下所示:
updateProduct(product: Product): Observable<Product> {
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
const url = `${this.productsUrl}/${product.id}`;
return this.http.put<Product>(url, product, { headers: headers })
.pipe(
tap(() => console.log('updateProduct: ' + product.id)),
// Return the product on an update
map(() => product),
catchError(this.handleError)
);
}
updateProduct(产品:产品):可观察{
const headers=new-HttpHeaders({'Content-Type':'application/json'});
常量url=`${this.productsUrl}/${product.id}`;
返回this.http.put(url,product,{headers:headers})
.烟斗(
轻触(()=>console.log('updateProduct:'+product.id)),
//在更新时返回产品
映射(()=>产品),
catchError(this.handleError)
);
}
请注意,我没有对传递的数据进行字符串化。我也不能把结果变成承诺
关于您的代码:
1)考虑将数据访问代码移动到服务中。
2) 您在哪里使用UpdatePerson
功能?(它叫什么名字?)
3) 当使用函数
关键字而不是箭头函数构建函数时,此
的作用域变为该函数,并且您实际上没有访问类级别的personObj
4) 我不清楚是否需要person
和personObj
如果您想要一些具有创建、更新和删除操作的工作示例代码,您可以在这里找到一个示例:
您可以在这里的stackblitz中看到/执行它:Wow!伟大的后德博拉!这是我工作的回购协议。基本上,我所改变的是从产品到人的模式。我将查看您分享的回购协议,并研究您提出的建议。非常感谢。快速看一眼。。。我认为这更像是一个演示应用程序,而不是一个为实际应用程序构建的示例。最佳实践是使用服务进行数据访问。从角度文档: