【问题标题】:Error in template parse errors in component angular 9组件角度9中的模板解析错误错误
【发布时间】:2020-05-24 18:17:53
【问题描述】:

我的疑问是以下一个我有两个组件,一个是演示文稿,另一个是角度 9 的容器,当我尝试在组件容器中导入演示文稿的组件时给我一个语法错误我希望你能帮助解决这个问题.谢谢

当前天气.component.ts

import { Component, OnInit } from '@angular/core';
import { CurrentWeatherService } from '../services/current-weather.service';

@Component({
  selector: 'app-current-weather',
  templateUrl: './current-weather.component.html',
  styleUrls: ['./current-weather.component.scss'],
})
export class CurrentWeatherComponent implements OnInit {
  constructor(public weatherService: CurrentWeatherService) {}

  ngOnInit() {

  }
}

天气卡.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { Weather } from 'src/structures/weather.structure';

@Component({
  selector: 'app-weather-card',
  templateUrl: './weather-card.component.html',
  styleUrls: ['./weather-card.component.scss']
})
export class WeatherCardComponent implements OnInit {

  @Input() weather : Weather;

  constructor() { }

  ngOnInit(): void {
  }

}

当前天气.component.html

<app-weather-card [weather]="weatherService.weather$ | async as weather" ></app-weather-card>

模板解析错误中的错误: 解析器错误:[weatherService.weather$ | 中的第 33 列出现意外标记“as”异步天气] 在 C:/Projects/projects-angular/weatherapp/src/app/current-weather/current-weather.component.html@0:29 ("]weatherService.weather$ | 异步天气" >") : C:/Projects/projects-angular/weatherapp/src/app/current-weather/current-weather.component.html@0:29

【问题讨论】:

  • 你需要'as weather'吗?
  • 好像错误来自模板,也为它做postcode。
  • 为什么需要as weather
  • 因为它是一项服务,我有一个 observable 在应用程序中获取我从 api 获得的一些数据,相同的语法在前面的组件中有它,它工作正常没有问题
  • 谢谢你,我可以通过删除 as 天气来修复它,并且它有效。非常感谢您的帮助。

标签: angular


【解决方案1】:

xxx$ | async as xxx 语法仅在 *ngIf 指令中受支持。您遇到的错误是因为您在组件输入绑定中使用它。

如果您只订阅一次,则不需要它,但如果您真的想要,则需要执行以下操作:

<app-weather-card *ngIf="weatherService.weather$ | async as weather" [weather]="weather"></app-weather-card>

在文档中称为“将条件结果存储在变量中”:

您可能希望显示同一对象的一组属性。如果 您正在等待异步数据,对象可以是未定义的。在 在这种情况下,您可以使用 ngIf 并将条件的结果存储在 局部变量如下例所示。

此代码仅使用一个AsyncPipe,因此只有一个订阅 创建的。条件语句存储结果 userStream|async 在局部变量用户中。然后你可以绑定 本地用户重复。

https://angular.io/api/common/NgIf#storing-a-conditional-result-in-a-variable

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2019-01-13
    • 2016-09-24
    • 2018-01-27
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多