首页 文章

将JSON http响应绑定到Angular 6组件

提问于
浏览
-1

我从HttpClient GET方法得到的JSON响应低于此值

{
  shortDescription: "3", 
  promotionName: "2", 
  highResolutionImage: "4", 
  lowResolutionImage: "5", 
  promotionOrChallengeCode: "aaa"
}

Promotion.ts

export interface IPromotion
{

    PromotionOrChallengeCode:string;
    PromotionName:string;
    ShortDescription:string;
    HighResolutionImage:string;
    LowResolutionImage:string;
}

In my Component class

promotion:IPromotion;

onSubmit() : void {

    this.httpClient.get('http://localhost:8080/api/search/'+this.pcode )
    .subscribe((response:IPromotion) => 
          { 
            console.log(response);
            this.promotion = response; 
            console.log(this.promotion.PromotionOrChallengeCode);
          });
    }

在浏览器控制台中,我能够查看JSON响应(第一个控制台语句的输出) . 并且第二个控制台语句的输出显示为“未定义”

让我知道如何读取JSON数据并绑定到HTML元素

以下是我正在使用的当前Angular版本:

C:\Users\893108>ng -v

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 6.1.2
Node: 8.11.3
OS: win32 ia32
Angular:
...

Package                      Version
------------------------------------------------------

rxjs                         6.2.2

typescript                   2.7.2

2 回答

  • 1

    将您的界面更改为您的JSON,您可以使用 JSON2TS

    export interface RootObject {
            shortDescription: string;
            promotionName: string;
            highResolutionImage: string;
            lowResolutionImage: string;
            promotionOrChallengeCode: string;
    }
    

    并使用它访问它

    console.log(this.promotion.promotionOrChallengeCode);
    
  • 1

    问题是您的json接口需要与api的响应具有相同的大小写 . 此外,您需要将HttpClient交给角度接口的通用签名 .

    export interface IPromotion
    {
    
        promotionOrChallengeCode: string;
        promotionName: string;
        shortDescription: string;
        highResolutionImage: string;
        lowResolutionImage: string;
    }
    
    promotion:IPromotion;
    
    onSubmit() : void {
    
        this.httpClient.get<IPromotion>('http://localhost:8080/api/search/'+this.pcode )
        .subscribe((response:IPromotion) => 
              { 
                console.log(response);
                this.promotion = response; 
                console.log(this.promotion.promotionOrChallengeCode);
              });
        }
    

相关问题