如何将从api获取的Id传递给angular方法?

如何将从api获取的Id传递给angular方法?,angular,Angular,我希望在单击列表中的店铺名称后,能够显示店铺名称。下面是我到目前为止的代码,它不工作!我已经尝试过修改HTML模板,特别是(代码)=”部分。我做错什么了吗?我现在已经让它工作了,但是收到一个错误“无法读取未定义的属性'name' Shops.ts 从“@angular/core”导入{Component,OnInit}; 从'@angular/common/http'导入{HttpClient}; @组成部分({ 选择器:“应用商店”, templateUrl:“./shops.componen

我希望在单击列表中的店铺名称后,能够显示店铺名称。下面是我到目前为止的代码,它不工作!我已经尝试过修改HTML模板,特别是(代码)=”部分。我做错什么了吗?我现在已经让它工作了,但是收到一个错误“无法读取未定义的属性'name'

Shops.ts
从“@angular/core”导入{Component,OnInit};
从'@angular/common/http'导入{HttpClient};
@组成部分({
选择器:“应用商店”,
templateUrl:“./shops.component.html”,
样式URL:['./shops.component.css']
})
导出类ShopsComponent实现OnInit{
商店:任何;
商店:任何;
构造函数(私有http:HttpClient){}
恩戈尼尼特(){
这个。getShops();
}
getShops(){
this.http.get('https://localhost:44366/api/shops)。订阅(响应=>{
这是我的回答;
},错误=>{
console.log(错误);
});
}
getShop(id:编号){
this.http.get('https://localhost:44366/api/shops/'+id).订阅(响应=>{
this.shop=响应;
},错误=>{
console.log(错误);
});
}
}
Shops.html

  • {{s.address}
  • {{shop.name}


    您的shop变量在初始情况下没有任何值。它没有定义。所以,要么在ngOnInit()部分中为shop变量赋值,要么使用安全导航符号(?)

    {{shop?.name}

    <ul *ngFor="let s of shops">
      <li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
      <li>{{s.address}}</li>
    </ul>
    
    <p>{{shop?.name}}</p>
    
    
    
  • {{s.address}
  • {{shop?.name}

    <ul *ngFor="let s of shops">
      <li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
      <li>{{s.address}}</li>
    </ul>
    
    <p>{{shop?.name}}</p>
    
    要检查shop变量的内容,请使用此代码

    <p>{{shop | json }}
    
    {{shop|json}
    
    尝试传递整个对象,并在从异步调用检索店铺名称时使用安全导航操作符显示店铺名称

    <ul *ngFor="let s of shops">
      <li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
      <li>{{s.address}}</li>
    </ul>
    
    <p>{{shop?.name}}</p>
    
    
    
  • {{s.address}
  • {{shop?.name}

    <ul *ngFor="let s of shops">
      <li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
      <li>{{s.address}}</li>
    </ul>
    
    <p>{{shop?.name}}</p>
    

    无论如何,最好创建一个
    接口
    来处理模板上的对象。

    当我收到一个JSON对象时,我应该先在ts文件中将我的shop变量初始化为type object

    shop: {};
    
    然后,我不得不进入我的HTML模板,稍微修改一下代码

    <p>{{shop?.name}}</p>
    
    {{shop?.name}

    <ul *ngFor="let s of shops">
      <li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
      <li>{{s.address}}</li>
    </ul>
    
    <p>{{shop?.name}}</p>
    

    看来正确的方法是创建一个接口。我现在将研究该解决方案。

    嘿,阿米特,您的解决方案有效,但它确实在我的IDE中引发了另一个错误。“[Angular]标识符'name'未定义。“\uuu对象”不包含此类成员。“我应该使用Angular模型吗?@Russell Hi,请在从api响应分配值后使用控制台日志(shop)或使用{{shop | json}}检查您的商店内容!”!我对Angular非常生疏。谢谢@Sajeetharan。你是一个伟大的StackOverflow用户。