angular5 - Angular 5无法从组件函数将数据设置为ngmodel

标签 angular5 angular-ngmodel

在我的 Angular 5 项目中,我可以从 ngModel 事件获取数据,但在进行一些 REST API 调用后无法为其设置数据。我尝试从 REST API 调用中检索一些数据,并从成分。这是我的代码。

app.component.ts:

  import {Component,OnInit} from '@angular/core';
  import {RestApiService} from "./rest-api.service";

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent implements OnInit{
    name: string = "";
    email: string = "";
    pass: any = "";
    users=[];
    count:number=0;
    constructor(private _rest: RestApiService) {

    }
    ngOnInit(){
      this.count=this.users.length;
      this.getUsers();
    }
    submit() {
      this._rest.postData({username: this.name, email: this.email, password: this.pass}).subscribe(function (data) {
        console.log(JSON.stringify(data));
        this.name = "";
        this.email = "";
        this.pass = "";
      }, function (err) {
        console.log(err);
      })
    }
    getUsers(){
      this._rest.getUsers().subscribe(function (data) {
        this.email=data[0].email;   // can't bind data to model
        this.users=data;           // can't use it for ngFor
        this.count=this.users.length;
      },function (err) {
          console.log(err)
      })
    }

  }

app.component.html:

<!--The content below is only a placeholder and can be replaced.-->
  <div class="container mar-top">
    <div class="col">
      <div class="form-group row">
        <label for="name" class="col-sm-2 col-form-label">Name</label>
        <div class="col-sm-6">
          <input type="text" class="form-control" id="name" placeholder="Name"  [(ngModel)]="name">
        </div>
      </div>
      <div class="form-group row">
        <label for="email" class="col-sm-2 col-form-label">Email</label>
        <div class="col-sm-6">
          <input type="text" class="form-control" id="email" placeholder="email@example.com"
                 [(ngModel)]="email">
        </div>
      </div>
      <div class="form-group row">
        <label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
        <div class="col-sm-6">
          <input type="password" class="form-control" id="inputPassword" placeholder="Password"
                 [(ngModel)]="pass">
        </div>
      </div>
      <div class="form-group row">
        <button type="submit" class="btn btn-primary mb-2" (click)="submit()">Submit</button>
      </div>
      <div>
        {{count}}
      </div>
    </div>
  </div>
  <div class="container mar-top">
    <div class="col">
      <table class="table">
        <thead>
          <tr>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
            <th scope="col">Password</th>
          </tr>
        </thead>
        <tbody *ngFor="let user of users;">
            <tr>
              <td>
                {{user.username}}
              </td>
              <td>
                {{user.email}}
              </td>
              <td>
                {{user.password}}
              </td>
            </tr>
        </tbody>
      </table>
    </div>
  </div>
  <router-outlet></router-outlet>

rest-api.service.ts:

import { Injectable } from '@angular/core';
  import {HttpClient,HttpHeaders} from "@angular/common/http";


  const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };
  @Injectable()
  export class RestApiService {

    constructor(private http:HttpClient) { }
    apiRoot:string="http://127.0.0.1:3001";

    postData(data){
      console.log(JSON.stringify(data));
      return this.http.post(this.apiRoot+'/insertuser', data,httpOptions);
    }
    getUsers(){
      return this.http.get(this.apiRoot+'/getusers');
    }
  }

在其余 API 调用之后,我无法在 HTML 文件中设置数据。尽管我在函数内设置了值,但值没有更改。

最佳答案

在 getUser 函数中使用箭头运算符,该关键字的范围在回调函数中发生了变化,因此,使用箭头运算符来防止这种变化。

import {Component,OnInit} from '@angular/core';
  import {RestApiService} from "./rest-api.service";

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent implements OnInit{
    name: string = "";
    email: string = "";
    pass: any = "";
    users=[];
    count:number=0;
    constructor(private _rest: RestApiService) {

    }
    ngOnInit(){
      this.count=this.users.length;
      this.getUsers();
    }
    submit() {
      this._rest.postData({username: this.name, email: this.email, password: this.pass}).subscribe(function (data) {
        console.log(JSON.stringify(data));
        this.name = "";
        this.email = "";
        this.pass = "";
      }, function (err) {
        console.log(err);
      })
    }
    getUsers(){
      this._rest.getUsers().subscribe((data) => {
        this.email=data[0].email;   // can't bind data to model
        this.users=data;           // can't use it for ngFor
        this.count=this.users.length;

      },function (err) {
          console.log(err)
      })
    }

  }

关于angular5 - Angular 5无法从组件函数将数据设置为ngmodel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50043354/

相关文章:

php - 如何在 Laravel 中部署 Angular 5 项目?

json - 角度 6 指定的命令 ("deploy") 无效。有关可用选项的列表,请运行 "ng help"

angular - 如何保存 *ngFor 生成的输入数据

angular - 当我操作 ngModelChange 中的更新值时,ngModel 更新未反射(reflect)出来

javascript - Angular select 不响应 ng-model 更改

html - 如何在 Angular2 中使用 *ngFor 动态生成 ngModel?

angular - NgModel 不工作。共享组件

regex - 仅用于数字的 Angular 5 Validators.pattern 正则表达式

angular - observable 类型中不存在属性间隔

javascript - Angular.js - ng-model 在文本输入上覆盖我的 ng-value