首页 > 解决方案 > 使用同一组件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);
  }

标签: angulartypescriptangular-ngmodel

解决方案


您在 testService 的 addUser 函数中发送 newUser。因此,您必须像使用用户变量一样使用空值声明 newUser。而且您还必须在 html 中绑定 newUser。


推荐阅读