【问题标题】:Angular - pass data between componentsAngular - 在组件之间传递数据
【发布时间】:2021-05-25 21:50:38
【问题描述】:

我正在开发一个 Web 应用程序,我使用 Angular 作为前端,使用 .Net 作为后端,我对这两种技术都很陌生。我有一个存储在 SQL Server 中的数据库,我使用 C# 类获取数据,并使用一些控制器将其传递给前端。我有一个 api.server.ts 文件,它从控制器调用函数,这些函数用于我的应用程序中的所有组件。我有一个组件,我在其中获取一系列产品(数据库中的所有产品)并在 html 中显示它们(使用 ngfor),以及每个产品的按钮。我想要做的是当我按下按钮将我重定向到另一个组件(这是一个新页面)并显示有关该特定产品的详细信息时。

这是我在前端控制器中使用该功能的地方(我认为显示该功能没有用,因为它工作正常):

  getProducts() {
    return this.http.get(this.baseUrl + '/Product/GetAll', { headers: this.header });
  }

这是我展示产品的 html 部分。 “Vezi produs”按钮将我重定向到另一个组件,我想在其中查看某个特定产品的产品信息。我尝试使用插值来获取产品 ID 并将其返回到 api.service.ts(从第一个组件设置来自 api.service.ts 的产品变量的值),然后我想在另一个组件中显示它组件(使用this.api.product),但似乎我不能使用插值。

  <div *ngFor="let product of products;">
        <div class="card" style="width: 15rem; height: 25rem; position:relative; margin-left:40px;">
          <img src={{product.picture}} class="card-img-top" alt={{product.name}} style="width:15rem; height:13rem;">
          <div class="card-body">
            <h5 class="card-title"><b>{{product.name}}</b></h5>
            <p class="card-text">{{product.description}}.</p>
            <table>
              <tr>
                <td>
                  <a href="#" class="btn btn-primary" id="veziprodus" (onclick)="getProduct({{product.Id}});" [routerLinkActive]="['link-active']" [routerLink]='["/view-product"]'>Vezi produs</a>
                </td>
                <td>
                  <p style="position:absolute; bottom:10px; right:10px;">
                    <b> {{product.price}} lei </b>
                  </p>
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>

另外,我也遇到了“兄弟”组件的问题。我真的不知道我的想法是不是很好,我是否真的可以从第一个组件中设置 api.product 值,然后使用相同的变量在第二个组件中显示它。

【问题讨论】:

    标签: c# asp.net .net angular typescript


    【解决方案1】:

    您可以做的一种方法是为此创建一个路由并在点击时导航到相关视图。

     <a [routerLink]="['/product', product.Id">
    

    在路由模块上,您可以创建类似的路径

    { path: 'product/:id', component:ProductDetailComponent }
    

    然后在视图组件中接收传递的id

     constructor(private route: ActivatedRoute) { }
    
    ngOnInit() {
      this.route.params.subscribe(params => {
         console.log(params) //log the entire params object
         console.log(params['id']) //log the value of id
       });
     }
    

    之后你可以用 id 提出请求,并随意使用它。

    【讨论】:

      【解决方案2】:

      一种方法是我们在 Angular 中支持路由器。您可以设置应用程序,使您的产品列表组件在一个页面上(比如说根 / ),然后您在另一条路线(即 /product)上有一个产品详细信息组件。当用户单击您列表中的按钮时,您使用路由器服务导航到 /product 页面,将产品标识符作为查询参数传递。产品详细信息将进行另一个后端调用并呈现产品详细信息。

      角度“英雄之旅”教程中很好地描述了这个和相关概念:https://angular.io/tutorial

      【讨论】:

        【解决方案3】:

        只要把这个(onclick)="getProduct({{product.Id}})改成(onclick)="getProduct(product.Id);,js代码就不需要{{}}

        【讨论】:

          【解决方案4】:

          Angular 文档中提供的常用方法是使用Route Parameters

          在路由模块中应该有如下内容:

          const someRoutes: Routes = [
            { path: 'products-list', component: ProductsListComponent },
            { path: 'product/:id', component: ProductItemComponent }
          ];
          

          在 ProductItemComponent 中,可以从路由参数中获取产品 id:

          @Component({
            selector: 'app-product-item',
            templateUrl: './product-item.component.html',
            styleUrls: ['./product-item.component.css']
          })
          export class ProductItemComponent implements OnInit {
            product$!: Observable<Hero>;
          
            constructor(
              private route: ActivatedRoute,
              private router: Router,
              private service: ProductsService
            ) {}
          
          
            ngOnInit() {
              this.product$ = this.route.paramMap.pipe(
                switchMap((params: ParamMap) =>
                  this.service.getProduct(params.get('id')!))
              );
            }
          }
          

          我采用了 Angular 的示例,并在 StackBlitz here 上做了一小部分。 (英雄详情为产品,英雄列表为产品)

          【讨论】:

            猜你喜欢
            • 2017-08-12
            • 1970-01-01
            • 2021-04-13
            • 2018-02-22
            • 2020-10-10
            • 2020-07-23
            • 2021-04-02
            • 2019-03-20
            相关资源
            最近更新 更多