Search code examples
angularangular2-servicesangular2-http

Make "view more detail" work in Angular 2/4


I've a problem having "view more detail" function work in my Angular app. This is pretty simple but i can't get the value of the details of a certain news that i clicked. This is how it works, first, you have a list of news and each news has a "view" button which can redirect you to a new page. How can i display the value of details of a certain news? The problem is on the news-detail.component.ts

news.service.ts

@Injectable()
export class NewsService {
    constructor(private httpClient: HttpClient) {
  }

getAllNews() {
    const authToken = localStorage.getItem('auth_token'); 
    const headers = new HttpHeaders() 
    .set('Content-Type', 'application/json') 
    .set('Authorization', `Bearer ${authToken}`);

    return this.httpClient
      .get('http://sample/news/', { headers: headers })
      .map(
        (response => response));
}


getNews(index: number) {

  }

}

news-list.component.ts

<div class="card" *ngFor="let newslist of newslists">
    <div class="card-header"> <button class=" btn btn-danger pull-right" style="cursor: pointer;" (click)="onViewNewsDetail(newslist.id)">View</button> 
        {{newslist.category}}          
    </div>
    <div class="card-body">
        {{newslist.title}}   
    </div>
  </div>

news-list.component.ts

export class NewsListComponent implements OnInit {
  newslists: any;
  constructor(private newsService: NewsService, private router: Router, private route: ActivatedRoute) { }

  ngOnInit() {

    this.newsService.getAllNews()
      .subscribe(
        (data:any) => {
          console.log(data);
          this.newslists = data.data.data;
          console.log(this.newslists);
        },
        error => {
          alert("ERROR");
        });
  }

  onViewNewsDetail(id: number){
    console.log(id);
    this.router.navigate(['news', id]);
  }

}

news-detail.component.ts

    export class NewsDetailComponent implements OnInit {
    id: number;
    news: number;

  constructor(private route: ActivatedRoute,
              private router: Router,
              private newsService: NewsService) { }

    ngOnInit() {
      this.route.params
        .subscribe((params: Params) => {
          this.id = +params['id'];
          // this.news = this.newsService.getNews(this.id);
        });
    }      
}

Solution

  • If you dont have endpoint for getting a single news article so maybe something like this will work for you.

    Service

    getNews(id: number) {
      return this.getAllNews().map((data: any) => data.data.data.find(news => news.id === id))
    }
    

    news-detail.component.ts

    ngOnInit() {
      this.route.params
        .subscribe((params: Params) => {
           this.id = +params['id'];
           this.newsService.getNews(this.id)
             .subscribe(news => this.news = news)
      });
    }