我试图建立一个简单的博客与Angular 2和Firebase,我有问题使用异步管道在一个组件.我在控制台中看到错误.

zone.js:344未处理的promise 拒绝:模板解析错误: 找不到管道‘Async’("

[ERROR ->]{{ (blog.user | async)?.first_name }}

"): BlogComponent@6:3 ; 区域:;任务:promise .然后值:错误:模板分析错误:(…)错误:模板分析错误:

blog.component.ts

import {Component, Input} from "@angular/core";

@Component({
  selector: 'blog-component',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.css'],
})

export class BlogComponent {
  @Input() blog;
}

blog.component.html

<h1 class="article-title">{{ blog.title }}</h1>
<p>{{ (blog.user | async)?.first_name }}</p>

app.component.ts

import { Component } from '@angular/core';
import { BlogService } from "./services/services.module";

@Component({
  selector: 'app-root',
  templateUrl: './应用程序.组成部分html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  constructor(private blogService: BlogService) {}
  articles = this.blogService.getAllArticles();
}

应用程序.组成部分html

<article *ngFor="let article of articles | async">
  <blog-component [blog]="article"></blog-component>
</article>

blog.service.ts

import {Injectable} from "@angular/core";
import {AngularFire} from "angularfire2";
import {Observable} from "rxjs";
import "rxjs/add/operator/map";

@Injectable()
export class BlogService {
  constructor(private af: AngularFire) { }

  getAllArticles(): Observable<any[]> {
    return this.af.database.list('articles', {
      query: {
        orderByKey: true,
        limitToLast: 10
      }
    }).map((articles) => {
      return articles.map((article) => {
        article.user = this.af.database.object(`/users/${article.user_id}`);
        return article;
      });
    });
  }
}

The problem arises only when I try to use async in blog.component.html file. It works if I try to print the user name in 应用程序.组成部分html file. Should I be injecting AsyncPipe in blog.module.ts? How can I get the async working in blog.component.ts?

推荐答案

@NgModule.declarations不是由子模块继承的.如果需要模块中的管道、指令和组件,则应将模块导入到功能模块中.

带有所有核心管道的模块是@angular/common中的CommonModule

import { CommonModule } from '@angular/common';

@NgModule({
  imports: [ CommonModule ]
})
class BlogModule {}

它在app.component中起作用的原因是,您很可能正在将BrowserModule导入AppModule.BrowserModule再出口CommonModule,所以进口BrowserModule就像进口CommonModule.

同样值得注意的是,CommonModule也有核心指令,比如ngForngIf.因此,如果您有一个使用这些功能的功能模块,您还需要将CommonModule导入该模块.

Angular相关问答推荐

当我试图将日期放在x轴上时,Angular Highcharts区域平面图不工作

使用多个管道时Angel 17空数据

声明Angular material 中按钮的自定义 colored颜色

带独立零部件的TranslateLoader[Angular 16]

使用 TAB 键时如何聚焦mat-select组件?

无法创建新的 Ionic 项目

使用Dragula时,ReactiveForm元素在拖动副本中显示不同的