我无法在html组件中显示服务结果

时间:2019-02-12 23:48:03

标签: .net typescript asp.net-core angular7 angular-components

/* I am developing an example application with asp net core Web Api and angular 7. This should consume a service, but when I try to show it in the component it shows me that the object is undefined.*/

//Shortn.ts

enter code here
export interface Shortn {

  Url: string;
}
//HomeComponent.ts
MyMethod() {

    var url = (<HTMLInputElement>document.getElementById("MyObjectInput")).value;
    alert("desde componente: " + url);
    this.shortenerService.shortenUrl2(url).toPromise()
      .then(res => this.shortener = res as Shortn);

  }
//ShortenService .ts

import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Shortn } from '../models/shortn';

//ShortenService 
@Injectable()
export class ShortenService {
  private apiURL = this.baseUrl + "api/My/Generate";
  constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) { }
  shortenUrl(url: string): Observable<string> {
    alert("desde servicio: " + url);
    let shortener = { Url: url };
    //shortener.Url = url;
    return this.http.post<string>(this.apiURL, shortener);
  }
  shortenUrl2(url: string): Observable<Shortn> {
    alert("desde servicio: " + url);
    let shortener = { Url: url };
    //shortener.Url = url;
    return this.http.post<Shortn>(this.apiURL, shortener);
  }
  shortenUrl3(url: string): Observable<Shortn> {
    let shortener = { Url: url };
    return this.http.post<Shortn>(this.apiURL, shortener);
  }

}
//home.component.html
<pre>
  {{shortener.Url}}
</pre>

通过按下按钮,应用程序可以正确访问服务(通过邮递员,我可以正确执行此操作),但是想要在home.component.html中显示它,则告诉我起酥油未定义。尝试不同的方法,但总是得到相同的结果 元素的版本为: 角CLI:7.2.3 节点:11.6.0 操作系统:win32 x64 ASP Net Core 2.2

能帮我吗?事先非常感谢

1 个答案:

答案 0 :(得分:0)

检查代码中的以下问题:

  1. Js区分大小写,您应该定义url: string;,因为从Web api返回的json是{"url":"api/My/Generate"}

    export interface Shortn {
        url: string;
    }
    
  2. 您需要更改未定义的shortener或将其初始化,因为在使用前可能没有设置它。

选项1:

    {{shortener ? shortener.url : "" }}

选项2:

private shortener: Shortn = { url:""};