【问题标题】:Agular not passing object to html pageAngular没有将对象传递给html页面
【发布时间】:2022-01-19 21:56:17
【问题描述】:

我在学习 Angular 方面遇到了问题,以前我没有遇到过这些问题,但是现在当我做这些演示时,一切都很好,直到我从使用 *.component.ts 文件中直接定义的对象切换到从其他地方拉出物体。在使用 2 种不同机制(微服务、直接服务对象的服务组件)的 2 个不同实例中。这个特别的就是最好的例子。下面的代码可以正常工作,但下面的代码不会将卡片对象传递给页面。调试显示对象正在被填充,但是当它到达 html 页面时它是未定义的。

        
import { Component } from '@angular/core';
import { map } from 'rxjs/operators';
import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { AppService } from '../app.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
  /** Based on the screen size, switch from standard to one column per row */
  //cards = [];
  cardsForHandset = [];
  cardsForWeb = [];

  //isHandset: boolean = false;
  cards = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
    map(({ matches }) => {
      if (matches) {
        return [
          { title: 'Card 1', cols: 2, rows: 1 },
          { title: 'Card 2', cols: 2, rows: 1 },
          { title: 'Card 3', cols: 2, rows: 1 },
          { title: 'Card 4', cols: 2, rows: 1 }
        ];
      }
      return [
        { title: 'Card 1', cols: 2, rows: 1 },
        { title: 'Card 2', cols: 1, rows: 1 },
        { title: 'Card 3', cols: 1, rows: 2 },
        { title: 'Card 4', cols: 1, rows: 1 }
      ];
    })
  );

  constructor(private breakpointObserver: BreakpointObserver,
    public appService: AppService,
    ) { }

}

HTML

<div class="grid-container">
  <h1 class="mat-h1">Todays Deals</h1>
  <mat-grid-list cols="2" rowHeight="350px">
    <mat-grid-tile *ngFor="let card of cards | async" [colspan]="card.cols" [rowspan]="card.rows">
      <mat-card class="dashboard-card">
        <mat-card-header>
          <mat-card-title>
            {{card.title}}
          </mat-card-title>
        </mat-card-header>
      </mat-card>
    </mat-grid-tile>
  </mat-grid-list>
</div>

这是行不通的代码。

        import { Component } from '@angular/core';
import { map } from 'rxjs/operators';
import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { AppService } from '../app.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
  /** Based on the screen size, switch from standard to one column per row */
  cards = [];
  cardsForHandset = [];
  cardsForWeb = [];

  isHandset: boolean = false;
  isHandsetObserver: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
    map(({ matches }) => {
      if (matches) {
        return true;
      }
      return false;
    })
  );

  constructor(private breakpointObserver: BreakpointObserver,
    public appService: AppService,
    ) { }

  ngOnInit() {
    this.isHandsetObserver.subscribe(currentObserverValue => {
      this.isHandset = currentObserverValue;
      this.loadCards();
      this.cards.push();
    });

    this.appService.getDeals().subscribe(
      response => {
        this.cardsForHandset = response.handsetCards;
        this.cardsForWeb = response.webCards;
        this.loadCards();
      },
      error => {
        // alert('There was an error in receiving data from server. Please come again later!');
       }
    );
  }

  loadCards() {
    this.cards = this.isHandset ? this.cardsForHandset : this.cardsForWeb;
  }

}

HTML - 与上面相同,但删除了异步。

服务

        import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AppService {

  constructor(public httpClient:HttpClient) { }

  getDeals(): Observable<any> {
    return this.httpClient.get('http://localhost:3000/deals');
  }
}

服务器端微服务

        var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  let jsaonResponse = {
    "handsetCards": [
      { title: 'Card 1', cols: 2, rows: 1 },
      { title: 'Card 2', cols: 2, rows: 1 },
      { title: 'Card 3', cols: 2, rows: 1 },
      { title: 'Card 4', cols: 2, rows: 1 }
    ],
    "webCards": [
      { title: 'Card 1', cols: 2, rows: 1 },
      { title: 'Card 2', cols: 1, rows: 1 },
      { title: 'Card 3', cols: 1, rows: 2 },
      { title: 'Card 4', cols: 1, rows: 1 }
    ]
  }

  res.json(jsaonResponse);
});

module.exports = router;

以下是错误:

Error Message

【问题讨论】:

    标签: javascript angular typescript rxjs


    【解决方案1】:

    这是打字稿打字错误。由于 cards 是一个数组,而您的 getDeals 返回单个对象打字稿不知道该类型是什么。 一个好的解决方案是创建一个模型:

    card.model.ts:

    export interface Cart {
      title: string;
      cols: number;
      rows: number;
    }
    

    app.service.ts 中的getDeals 将返回Card 的数组(不要忘记导入您的模型):

    getDeals(): Observable<Card[]> {
      return this.httpClient.get('http://localhost:3000/deals');
    }
    

    home.component.ts 中的变量如下所示:

    cards: Card[] = [];
    cardsForHandset: Card[] = [];
    cardsForWeb: Card[] = [];
    

    【讨论】:

    • 非常接近,最终将app.services.ts 中的getDeals() 留给getDeals():Observable&lt;any&gt; .. 并保留其余部分,效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2011-09-20
    • 1970-01-01
    • 2013-01-10
    相关资源
    最近更新 更多