将ID(索引)传递给onEditDetail()参数

时间:2017-08-29 09:46:43

标签: javascript angular parameters ngoninit

如何将值索引或id传递给EditDetail()参数。一旦我点击html中的onEditDetail(),我希望它被放在onEditDetail()的括号内

ngOnInit() {
  this.route.params
    .subscribe((params: Params) => {
      this.id = +params['id'];
      this.user = this.userService.getUser(this.id);
    });
}

onEditDetail(id: string) {
  console.log(id);
}
  

用户detail.component.html

 <div class="container">
  <div class = "row">
    <div class="col-md-3"></div>
    <div class = "col-md-8">
      <div class="card">
        <div class="card-header">
          {{ user.l_name}} 's Complete Information<span class="pull-right"><input class="form-control" placeholder="Search User" name="srch-term" id="srch-term" type="text"></span>
        </div> 
        <table class="table table-responsive">
          <thead class="thead-default">
            <tr>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Contact Number</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{{ user.f_name }}</td>
              <td>{{ user.l_name }}</td>
              <td>{{ user.contact_no }}</td>
              <td><button class=" btn btn-primary" style="cursor: pointer;" (click)="onEditDetail()">Edit</button> </td>
            </tr>
          </tbody>
        </table>     
      </div>
    </div>
  </div>
</div>

3 个答案:

答案 0 :(得分:1)

添加其他答案,

您需要了解您正在进行异步调用。

因此,如果您需要在其他任何地方访问id,则需要在完成异步调用时获取,而不是在此之前。

这就是原因,你需要在Subscribe块中调用onEditDetail()作为最后一个参数。 订阅有3个参数。

  1. 通过电话回复的数据
  2. 如果发生任何错误。
  3. 如果您想要做某事,请完成。
  4. 在您的情况下,作为第三个参数,您必须调用onEditDetail方法

    ngOnInit() {
      this.route.params
        .subscribe((params: Params) => {
          this.id = +params['id'];
          this.user = this.userService.getUser(this.id);
    
          // 3rd parameter, this is where call is subscribe is completed
          this.onEditDetail(this.id);
        });
    }
    

答案 1 :(得分:0)

你可以这样做

ngOnInit() {
  this.route.params
    .subscribe((params: Params) => {
      this.id = +params['id'];
      this.user = this.userService.getUser(this.id);

      // Your method call
      this.onEditDetail(this.id);
    });
}

onEditDetail(id: string) {
  console.log(id);
}

答案 2 :(得分:0)

ngOnInit() {
  this.route.params
    .subscribe((params: Params) => {
      this.id = +params['id'];
      this.onEditDetail(this.id); //call onEditDetails and pass id to it.
      this.user = this.userService.getUser(this.id);
    });
}

onEditDetail(id: any) {
  console.log(id);
}