パイプ「async」が見つかりませんでした 質問する

パイプ「async」が見つかりませんでした 質問する

Angular 2 と Firebase を使用して簡単なブログを作成しようとしていますが、コンポーネントで非同期パイプを使用する際に問題が発生しています。コンソールにエラーが表示されます。

zone.js:344未処理の Promise 拒否: テンプレート解析エラー: パイプ 'async' が見つかりませんでした ("

[エラー ->]{{ (blog.user | async)?.first_name }}

"): BlogComponent@6:3; ゾーン:; タス​​ク: Promise.then; 値: エラー: テンプレート解析エラー:(…) エラー: テンプレート解析エラー: パイプ 'async' が見つかりませんでした ("

ブログコンポーネント

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

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

export class BlogComponent {
  @Input() blog;
}

ブログコンポーネント

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

アプリコンポーネント

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

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

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

アプリコンポーネント

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

ブログサービス

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;
      });
    });
  }
}

問題は、blog.component.html ファイルで async を使用しようとした場合にのみ発生します。app.component.html ファイルでユーザー名を印刷しようとすると機能します。blog.module.ts に AsyncPipe を挿入する必要がありますか? blog.component.ts で async を機能させるにはどうすればよいですか?

ベストアンサー1

@NgModule.declarations子モジュールには継承されません。モジュールからパイプ、ディレクティブ、コンポーネントが必要な場合は、そのモジュールを機能モジュールにインポートする必要があります。

すべてのコアパイプを備えたモジュールCommonModule@angular/common

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

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

で動作する理由は、に をapp.componentインポートしている可能性が高いためです。は を再エクスポートするため、 をインポートすると もインポートすることになります。BrowserModuleAppModuleBrowserModuleCommonModuleBrowserModuleCommonModule

には、やCommonModuleのようなコア ディレクティブもあることにも注意してください。したがって、それらを使用する機能モジュールがある場合は、そのモジュールに もインポートする必要があります。ngForngIfCommonModule

おすすめ記事