【发布时间】:2021-05-25 12:46:46
【问题描述】:
我想使用我的变量(可以通过 [(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);
}
}
service.ts
addUser(newUser: TestUser): Observable<TestUser> {
return this.http.post<TestUser>(this.testUrl, newUser);
}
【问题讨论】:
标签: angular typescript angular-ngmodel