首页 > 解决方案 > 如何在 Angular 员工 component.html 上返回 EmployeeCode?

问题描述

问题

如何在 Angular 员工 component.html 上返回 EmployeeCode?

样本数据参考表

Code  tableName   FieldName   LabelText
111   Employees   EmployeeId  EmployeeCode

调用结果

GetLabelTextForEmployee('Employees','EmployeeId')

it suppose Return EmployeeCode

我在 angular 6 的 asp.net core 2.1 Web API 上工作。

我在 Web API 名称 GetReferenceFileData 上创建函数以从中获取标签文本

数据库并根据 Reference Table 显示在 employees.component.html 上。

这是我的功能:

[HttpGet("{tableName}/{FieldName}")]
        [Produces("text/plain")]
        public string GetReferenceFileData([FromRoute] string tableName, [FromRoute] string FieldName)
        {
          var Result =  (from h in _context.ReferenceFiles
                          where h.TableName == tableName && h.FieldName == FieldName
                          select h.LabelText).FirstOrDefault();
            if(Result==null)
            {
                Result = "Not Exist";
            }

            return (Result);


        }

上面的函数只返回一个字符串值作为标量值

我试过的:

1-在 API 服务上我创建下面的函数:

GetLabelTextForEmployee(tableName:string,FieldName : string)
              {
                return this.http.get('https://localhost:44326/api/reference/' + tableName + '/' + FieldName);
              }


on employee.component.html 

// 如何在这里使用函数 GetLabelTextForEmployee 来返回 EmployeeCode 我根据 post 中的存在来制作代码:

on employees.component.ts

    getEmployeeCode() {
       this.api.GetLabelTextForEmployee('Employees','EmployeeId')
       .subscribe( data=>{
         this.returnedData = data; //SUBSCRIBE HERE
         console.log(data);
       }); 
    }
on employees.component.html
 {{getEmployeeCode() | async}}

结果如下我得到 EmployeeCode 但在无限循环中并且没有在表单上显示为图像显示 后无限循环上的代码结果

标签: javascriptc#angularasp.net-core

解决方案


我假设你的意思是,当你打电话时GetLabelTextForEmployee()你没有得到结果(或者更确切地说,你没有得到你期望的结果)?

当您使用 Angular 的HttpClientHTTP 请求时,您必须订阅该方法,否则它永远不会真正执行。

在您的employee.component.ts中,您需要调用该函数,订阅它,并将结果分配给一个局部变量。然后,您可以在模板 ( employee.component.html) 中使用该局部变量;

以下假设您要在组件初始化时调用该函数,并且您的函数在服务调用ApiService中,并且您的 api 返回一个对象。

员工组件.ts

employee: any;

constructor(private apiService: ApiService) { }

ngOnInit() { 
    this.apiService.GetLabelTextForEmployee().subscribe(result => {
          this.employee = result;
    }
}

员工.component.html

现在,分配了局部变量后,您可以使用插值来显示该值。

例如

<span class="employee-code">{{employee.employeeCode}}</span>

同样,这是假设您的 API 返回一个对象,您在模板中使用{{employee.employeeCode}}.

如果您的 API 返回一个字符串,那么您只是在进行插值{{employee}}

编辑

如果你想直接从模板调用函数,你仍然使用插值,但由于你的函数在服务中,你需要在你的组件中有一个调用服务的函数。不建议直接从模板调用服务函数。

IE

员工组件.ts

getEmployeeCode() {
    return this.apiService.GetLabelTextForEmployee('Employees','EmployeeId');
}

员工.component.html

现在,您可以getEmployeeCode()从模板中调用,并使用async管道。

{{getEmployeeCode() | async}}

注意:使用管道时,您不需要GetLabelTextForEmployee()在组件方法 ( ) 中订阅。Angular 已经订阅了它,并在标记更改检测之前返回发出的最新值。getEmployeeCode()async

异步管道订阅 Observable 或 Promise 并返回它发出的最新值。当发出新值时,异步管道会标记要检查更改的组件。当组件被销毁时,异步管道会自动取消订阅以避免潜在的内存泄漏。


推荐阅读