【问题标题】:Angular 5 can't set data to ngmodel from component functionAngular 5 无法从组件函数将数据设置为 ngmodel
【发布时间】:2018-04-26 12:45:20
【问题描述】:

在我的 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 文件中设置数据。虽然我在函数内部设置了值,但值没有改变。

【问题讨论】:

    标签: angular5 angular-ngmodel


    【解决方案1】:

    在 getUser 函数中使用箭头操作符,回调函数中 this 关键字的作用域发生了变化,所以,使用箭头操作符来防止这种变化。

    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)
          })
        }
    
      }
    

    【讨论】:

    • 不,它不起作用。 this.ref.detetChanges() 抛出错误“无法读取未定义的属性 'detectChanges'”。
    • 现在尝试我已经使用箭头运算符解决了它以响应 getUsers 方法
    • 可能不需要更改检测,只需使用箭头运算符并尝试一下
    • 为 ngModel 设置了值,但无法将数据分配给 this.users
    • 更改表单后用户=[];给用户:对象=[];它正在工作
    猜你喜欢
    • 2018-08-30
    • 2020-10-10
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多