angular - 使用同一组件Angular 11中的变量在组件中创建新对象
问题描述
我想使用我的变量(可以通过 [(ngModel)] 在 html 中更改这些值)来创建类型为 Testuser 的新对象 newUser。
在 html 中有 firstName、lastName 等的输入字段,我想通过单击按钮将其发送到数据库。
第二行字段包含 firstName、lastName 等。如果我单击另一个按钮,我想在这些单独的字段中显示数据库的值。
组件.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);
}
}
服务.ts
addUser(newUser: TestUser): Observable<TestUser> {
return this.http.post<TestUser>(this.testUrl, newUser);
}
解决方案
您在 testService 的 addUser 函数中发送 newUser。因此,您必须像使用用户变量一样使用空值声明 newUser。而且您还必须在 html 中绑定 newUser。
推荐阅读
- javascript - JSON 检查约束
- javascript - Moongose 或 mongo 跳过分页返回空数组?
- objective-c - 如何从 AVPlayer 中的 mpd 文件中提取字幕?
- java - 在 Java 中通过套接字流同步变量
- java - Android:如何在循环中使用相同的 AlarmManager?
- vue.js - 缓存 MP3 音频文件以供离线访问
- string - 詹金斯:如何从变量设置正文内容
- android - 如何从 Java 代码处理 Kotlin 中的泛型
- typescript - 使用带有联合类型签名的索引类型的意外行为
- mysql - sql join 查询数据库,没有想要的结果,