如何解决使用同一组件Angular 11中的变量在组件中创建新对象
我想使用我的变量(可以通过 [(ngModel)] 在 html 中更改这些值)来创建 Testuser 类型的新对象 newUser。
在 html 中有 firstName、lastName 等的输入字段,我想通过单击按钮将其发送到数据库。
第二行字段包含 firstName、lastName 等。 如果我点击另一个按钮,我想在这些单独的字段中显示数据库的值。
component.ts
import {Component,OnInit} from '@angular/core';
import {TEST_USER_EMPTY,TestUser} from './testUser';
import {TestService} from './test.service';
@Component({
selector: 'app-test',templateUrl: './test.component.html',styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
id = 0;
lastName = '';
firstName = '';
isActive = true;
// user with empty content
user: TestUser = TEST_USER_EMPTY;
// todo create new user with ngModel values for add user
newUser: TestUser;
constructor(private testService: TestService) {
}
ngOnInit(): void {
this.fetchUserFromServiceId();
}
changeStatus(): void {
this.isActive = !this.isActive;
}
//this function works
fetchUserFromServiceId(): void {
console.log('%cWerte:','color: orange;',this.id,this.isActive,this.lastName,this.firstName);
this.testService.getUserById(this.id).subscribe(user => {
if (user) {
this.user = user;
} else {
alert('no user found');
}
});
}
// this function needs the variables from above,but doesn't accept it
addUserFromService(): void {
this.testService.addUser(this.newUser).subscribe(() => alert('Post done'));
}
showCurrentUser(): void {
console.log('ID:' + this.id + ' Last Name: ' + this.lastName + ' First Name: ' + this.firstName);
}
}
service.ts
addUser(newUser: TestUser): Observable<TestUser> {
return this.http.post<TestUser>(this.testUrl,newUser);
}
解决方法
您正在 testService 的 addUser 函数中发送 newUser。因此,您必须像使用 user 变量一样使用空值声明 newUser 。并且你还必须在 html 中绑定 newUser。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。