首页 > 解决方案 > 如何将值从模板 HTML 传递到组件,然后在服务中使用

问题描述

我想从 component.html 获取 id 到 component.ts 以将其传递给服务。

.ts 文件是;

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { HttpErrorResponse } from '@angular/common/http/src/response';
import { SendUsingApiService } from '../send-using-api.service';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { setDefaultService } from 'selenium-webdriver/chrome';

@Component({
  selector: 'app-org-info',
  templateUrl: './org-info.component.html',
  styleUrls: ['./org-info.component.css'],
  providers: [SendUsingApiService]
})

export class OrgInfoComponent implements OnInit {
  orgData: string[] = [];
  Id = 1;

  editRecord:FormGroup;
  constructor(private httpService: HttpClient, private _serv: SendUsingApiService, 
    private fb: FormBuilder, private _ar:ActivatedRoute, private _r:Router) {
      this.editRecord = this.fb.group({
        Id:['1', []],
        OrganisationName:['', []],
        ContactPerson:['', []],
        ContactPersonHPNo:['', []],
        ContactPersonEmailId:['', []]

      });
    }

  ngOnInit() {
    console.log(this._ar.snapshot.params.Id, "+ve");
    this._ar.params.subscribe(() => {
      this._serv.getUsers(this._ar.snapshot.params.Id).subscribe((res)=>{
        console.log(res);
        this.setUser(res);
      });
  });

}

我得到了 console.log(this._ar.snapshot.params.Id); 的值 作为未定义的“+ve”。

我想在控制台中获取 Id 值。

根据要求,我正在添加 html 部分,尽管调整很少;

<td style="text-align: center;">
            <a class="btn btn-basic" [routerLink]="['/org-info',data['Id']]" role="button" (click)="getOrgData(data.Id)">View</a>&nbsp;&nbsp;&nbsp;&nbsp;
          </td>

标签: angular5angular6

解决方案


我定义了一个属性而不是 Id = 1; (多于)

paramId = '';

然后,在 ngOnInit 中;

ngOnInit() {
this.paramId = this._ar.snapshot.params.Id;
console.log(paramId, "+ve");                                                         
}

这样做,我得到了 Id 值而不是未定义。


推荐阅读