简体   繁体   中英

Data is not displaying on template (Angular)

I am practicing Angular by doing simple project. I see all Q&A on SO which is quite similar with my problem. Reason is that I am trying to display the async data before it initialized into articles variable, but I have tried *ngIf and async pipe.

myService

 public getArticlesByCategory(): Observable<any> {
   return this.request.get(this.categoryURL) 
  }

myComponent.ts

  public articles: any[] = [];

  constructor(
    private articleService: ArticlesService
  ) { }

  ngOnInit(): void {
    this.articleService.getArticlesByCategory().subscribe({
      next: (data) => {
        this.articles = data.articles; 
        console.log(this.articles)
      },
      error: (error) => {
        console.log(error);
      }
    })
  }

template

<div *ngIf="articles">
    <div *ngFor="let article of articles">
        <p>{{article.title}}</p>
    </div>
</div>

After Reviewing your code I found following errors:-

  • In app.routing.module.ts in rediretTo add pathMatch:'full'
const routes: Routes = [
  { path: '', redirectTo: 'articles', pathMatch: 'full' },
  { path: 'articles', component: ArticlesComponent },
];
  • In app.module.ts add ArticlesComponent in declaration
@NgModule({
  declarations: [AppComponent, NavbarComponent, ArticlesComponent],
  imports: [
    // CommonModule,
    BrowserModule,
    RouterModule,
    HttpClientModule,
    AppRoutingModule,
  ],
  providers: [ArticlesService],
  bootstrap: [AppComponent],
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM