#Can't render entity

25 messages · Page 1 of 1 (latest)

winter radish
#

hello I am trying to render a single article by their id:

export class ArticleDetailsComponent {
  article: Article=<Article>{};

  constructor(private articleService: ArticleService) {}

  getArticle(id: string): void {
    this.articleService.get(id)
      .subscribe({
        next: (data) => {
          this.article = data;
          console.log(data);
        },
        error: (e) => console.error(e)
      });
  }
}

the html file:

@if (article) {
    <p>{{article.id}}</p>
    <p>{{article.title}}</p>
} 

why does it not get rendered? the component gets loaded, I've tested it on my browser

#

I would appreciate a good read on the topic

glad cedar
#

It's rendered as expected by your code: article: Article=<Article>{};

#

You never call the getArticlefunction

winter radish
#

where should I call the function

#

in the constructor maybe?

glad cedar
#

First problem to solve: you need the id.

winter radish
#
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Article } from '../model/article.model';

const baseUrl = 'http://localhost:8080/api/v1/articles';
@Injectable({
  providedIn: 'root'
})
export class ArticleService {

  constructor(private http: HttpClient) { }

  getAll(): Observable<Article[]> {
    return this.http.get<Article[]>(baseUrl);
  }

  get(id: any): Observable<Article> {
    return this.http.get<Article>(`${baseUrl}/${id}`);
  }
}

sorry for not pasting this

#

I get the id here

glad cedar
#

The component use the id to pass it to the service to get the Article

winter radish
#

ohhh

#

i see what you mean but I am not sure how to get the id

#

I thought a proper call on the browser would be sufficient

glad cedar
#

How would the browser knows the id?

#

Think about how you use the details component and how to retrive the id

winter radish
glad cedar
#

If the component is routed, pass it in the url.
If not, pass it as an @Input

winter radish
#

I am passing it in the url

#
export const routes: Routes = [
  { path: '', component: AppComponent, children: [
      { path: 'articles', component: MainContainerComponent },
      { path: 'articles/:id', component: ArticleDetailsComponent },
  ]  },  
];

URL: http://localhost:4200/articles/1

glad cedar
winter radish
#
export const routes: Routes = [
  { path: '', component: AppComponent, children: [
      { path: 'articles', component: MainContainerComponent },
      { path: 'articles/:id', component: ArticleDetailsComponent },
  ]  },  
];

I can't redirect ' ' to articles because redirecting to a child is not allowed. How do I make /articles the first thing to open when I launch my page

glad cedar
#

#questions message

winter radish
#

thanks and I am sorry