The pipe 'async' could not be found
Asked Answered
J

18

157

I am trying to build a simple blog with Angular 2 and Firebase and I am having issues using async pipe in a component. I get the error in the console.

zone.js:344Unhandled Promise rejection: Template parse errors: The pipe 'async' could not be found ("

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

"): BlogComponent@6:3 ; Zone: ; Task: Promise.then ; Value: Error: Template parse errors:(…) Error: Template parse errors: The pipe 'async' could not be found ("

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: './app.component.html',
  styleUrls: ['./app.component.css']
})

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

app.component.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 app.component.html file. Should I be injecting AsyncPipe in blog.module.ts? How can I get the async working in blog.component.ts?

Jaxartes answered 21/9, 2016 at 19:47 Comment(4)
Try adding CommonModule to your BlogModule's importsCollegiate
Awesome, Thanks much! That worked. Reply as answer and I'll mark as right answer.Jaxartes
thanks it worked :)Latoyialatreece
I was missing the component in the child module's declarations, that's why I was getting the error. If that helps someone.Pacesetter
C
246

@NgModule.declarations aren't inherited by child modules. If you need pipes, directives, components from a module, the module should be imported into your feature module.

The module with all the core pipes is CommonModule from @angular/common

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

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

The reason it works in the app.component is because you are most likely importing BrowserModule into the AppModule. BrowserModule re-exports CommonModule, so by importing BrowserModule, it's like also importing CommonModule.

It's also worth noting that CommonModule has the core directives also, like ngFor and ngIf. So if you have a feature module that uses those, you will also need to import the CommonModule into that module.

Collegiate answered 21/9, 2016 at 20:26 Comment(2)
This answer also fixed my situation where I was using the date pipe in a component that is declared/exported in a shared module. Thanks.Nicolanicolai
In addition to that, reordering @NgModule.imports array declarations solved my issue; hope it helps someone.Alluvium
M
75

If the component at the route you're loading is not declared (via declarations:[]) then you will also get this type of error.

Mesencephalon answered 22/6, 2020 at 18:38 Comment(7)
Or a subtle variation of this answer: forgetting to declare the component under test in your TestBed.configureTestingModule call. 🙈Asbestosis
Thank you. Everyone keeps talking about "You just have to import CommonModule" and nobody ever tells that this is also one of the reasons.Hydrostat
Thanks @Asbestosis I spent over an hour figuring out why I got this error even though I had imported CommonModuleDendroid
@StephaneJanicaud Yeah programming is fun, except when it's not 😅Asbestosis
@Asbestosis Yes, another thank you for the article you wrote about OAuth2 + OIDC and SPA, I think it'll also help me a lot with silent refresh issues I may encounter as I use the same library :)Dendroid
Or another subtle variation, when you add to the declarations for 1 module (for example using ng g c my-component), then move the component to another module and forget to move the declaration acrossAdelaadelaida
Either this or you did not define your route yet. Happened to me when I restructured my app and put a component into a new module with its own routing.Macle
K
22

When adding a new component in Angular 9 I had to restart the development server possibly also because of HMR:

ng serve --hmr

Without this the application simply did not load all the dependencies and issued this error.

Kulp answered 15/3, 2020 at 9:49 Comment(2)
This can also happen if you rearrange dependent services. For example I had a SavingsService that I split into SavingsService and SavingsUIService. After recompiling I got the real error, which was that the new service wasn't being provided anywhere. So yes this can definitely be a red herring requiring full recompilationJudon
@MikeGledhill I think this is related to the optimizations being performed when using HMR, to prevent reloading of the whole component tree. Most likely the package containing the async pipe is not injected for the new component.Kulp
A
19

Component you're trying to load is not declared in the declarations array then you will get this type of error, in my case this was shipping component, like mentioned below:

enter image description here

Apiece answered 12/3, 2021 at 7:13 Comment(1)
This answer would be better if the image was text instead of an image of text, or even if the text associated with the image was something other than "enter image description here"...Dilantin
P
16

If you tried all above mentioned answers but it is not working means , Just do npm run start it will work , In my case after some compilation issue this error came.

Popularity answered 14/5, 2020 at 11:18 Comment(2)
so wierd - but it help me to . probably it restart the angular server in a better way ?Alvy
Yes sometimes during a large refactor, this is the only solution...Belak
S
10

If you have upgraded to Angular 6 or 7, make sure in your tsconfig.ts turn off enableIvy in angularCompilerOptions

e.g:

angularCompilerOptions: {
enableIvy : false; // default is true
}

That solved my issue, may be it'll save someone else time too.

Seldan answered 2/11, 2018 at 14:50 Comment(8)
This does work, but I hope to see a real fix besides disabling core system functionality.Argentine
I was reading somewhere to import CommonModule globally can solve this issue too but I haven't tested yet.Seldan
Ivy is not production ready yet, so skip it for angular 7, enable for angular 8 onwardsAnalcite
Once they have Ivy ready for production, there might be other workaround for async pipe, I know people have already raised bug for this issue.Seldan
This solved my issue. Using Angular 7.2.4 and the async pipe extensively throughout the app, but sadly compiling for production fails with The pipe 'async' could not be found.. Disabling Ivy worked.Dickinson
Not the right answer. Disabling Ivy is a workaround.Rowney
As of Angular 9 I still see this issue. This answer is old and irrelevant now that Ivy is live.Lunch
This is a bandaid masking an underlying issue. It will get rid of the error and not the problem the error is about.Mesencephalon
S
7

I found the same problem some times when changing multiple imports at once.

My app worked back again just fine without changing any code but restarting ng start. One of the surprises of coding until late.

Normally this drives me crazy as I was checking all the imports, and the answer of the "Common Module" normally makes sense, but just in case someone finds the same silly situation I faced, now you know what to do.

Saltwater answered 4/5, 2020 at 23:43 Comment(1)
This was the case for me. I had made a change to a module and had to stop and restart the app. Thanks.Uticas
M
6

In my case the input to the pipe was null. So in the case of the question make sure that blog.user in <p>{{ (blog.user | async)?.first_name }}</p> is not null.

Madly answered 13/7, 2020 at 12:56 Comment(0)
V
5

If like me you're developing a standalone component,

I was missing the import

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

@Component({
   selector: 'test',
   standalone: true,
   imports: [
      AsyncPipe
   ],
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
Venue answered 5/11, 2022 at 18:35 Comment(0)
B
3

edit: I have been doing my own project, and I have noticed that this error might occur when code has any kind of build error, for example unclosed html tag like <label>foo<label>. After that, the only way I know, is to just reset the entire server. It is annoying and shouldn't be like that.


I got this error when I had an empty (actually commented) function implementation in my component

in html: <div (click)="onClickFoo()">

in .ts

onClickFoo() {
     // this.router.navigate([...])
}
Bruit answered 13/8, 2020 at 15:13 Comment(0)
A
2

Basic reason:

The pipe async is exported from the CommonModule and you will get this error when you forgot to import CommonModule either in the module importing your component or in the component itself (if you are in standalone mode.

Advanced one:

Now you might also get the "pipe async not found" if angular, for some reason, has not been able to preload properly the CommonModule.

To check if this is the case, you can force Angular preloading all the modules, changing your code as follows:

// Probably in app-routing.module.ts

import { RouterModule, PreloadAllModules } from '@angular/router';

RouterModule.forRoot([
], {
  // Add this property to your main router module
  preloadingStrategy: PreloadAllModules
})

Then reload the page, if the problem is gone, it very likely means angular is not able to resolve your routes dependencies properly. You could for instance have a module importing its routes but also importing another module itself importing its routes.

Artistry answered 29/11, 2022 at 9:41 Comment(0)
E
1

You can also get the same error if you are using multiple modules in your app.module.ts

import { MatCardModule } from '@angular/material';
import { AppComponent } from './app.component';

// module 1
@NgModule({ exports: [MatCardModule] })
export class MaterialModule {}

// module 2
@NgModule({
    imports: [MaterialModule]
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule {}

Then if you generate a component using the command:

ng generate component example

It gets added to the first module, instead of the second one:

import { MatCardModule } from '@angular/material';
import { AppComponent } from './app.component';
import { ExampleComponent } from './example/example.component';

// module 1
@NgModule({ exports: [MatCardModule], declarations: [ExampleComponent] })
export class MaterialModule {}

// module 2
@NgModule({
    imports: [MaterialModule]
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule {}

Which will create the same error! Moving the component to the AppModule will fix it.

@NgModule({
    imports: [MaterialModule]
    declarations: [AppComponent, ExampleComponent],
    bootstrap: [AppComponent]
})
export class AppModule {}
Ebsen answered 11/4, 2018 at 14:47 Comment(0)
J
1

If you're getting this in an optimized production build it could be due to tree shaking, especially if you're using sideEffects: false. This is now an encouraged setting in Angular 10 via ng new --strict.

Still have yet to figure out how to fix my project, but setting it to true fixed it for me for now.

Judon answered 28/6, 2020 at 17:14 Comment(0)
L
1

Previous answers are good (remember to do declarations:[]), but also remember to restart your watch (only if you're using CMD npm-run webpack-development -- -- progress --watch.

Lakieshalakin answered 6/7, 2022 at 14:1 Comment(0)
C
0

I faced this issue when I tried to use the async pipe in a component used as a dialog. I solved this by declaring the component in the immediate module (I used lazy loading). The app module if you are not.

Circumfluent answered 17/4, 2021 at 15:57 Comment(0)
N
0

Also, make sure that you're importing the module that the component is declared in.

Necropsy answered 14/10, 2022 at 6:57 Comment(0)
M
0

Changing the name of a component could also cause this error, and you can solve this by manually checking the imports in the app module, because it will probably be messed up.

Maurinemaurise answered 15/7, 2023 at 14:44 Comment(0)
A
0

If you are using a STANDALONE component, add "CommonModule" to the imports[CommonModule] @Component metadata.

e.g.

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

@Component({
  selector: 'a-standalone-component',
  standalone: true,
  imports: [CommonModule],

  template: `testMsg$ {{testMsg$ | async}}
Aida answered 14/11, 2023 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.