0

I have getNewsDetail() function that subscribes to an http get request. Then it stores in detailNews attribute what the function returns. The code works fine detailNews.created[0].value returns its value, however, in console I get ERROR TypeError: ctx.detailNews.created is undefined.

news.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
import { INewsDetail } from '../../interfaces/news-detail';

@Injectable({
  providedIn: 'root'
})
export class NewsService {

  constructor(private http: HttpClient) { }

  getNewsDetail(id):Observable<INewsDetail> {
    return this.http.get(`${environment.url}`+`/node/`+id+`?_format=json`);
  }
}

news-detail.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NewsService } from 'src/app/core/services/news/news.service';

@Component({
  selector: 'app-news-detail',
  templateUrl: './news-detail.component.html',
  styleUrls: [ './news-detail.component.scss']
})
export class NewsDetailComponent implements OnInit {
  detailNewsID: '';
  detailNews: any = {};

  constructor(
    private newsService: NewsService,
    private activatedRoute: ActivatedRoute
  ) { }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(params => {
      this.detailNewsID = params.id;
    });

    this.getNewsDetail(); 
  }

  getNewsDetail() {
    this.newsService.getNewsDetail(this.detailNewsID).subscribe(news => {
      this.detailNews = news;
    });
  }
}

news-detail.component.html

{{ detailNews }} // Renders: [object Object] 
{{ detailNews.created[0].value }} // It renders the value, but console shows ERROR TypeError: ctx.detailNews.created is undefined.
Ricardo Castañeda
  • 5,746
  • 6
  • 28
  • 41
  • {{ detailNews?.created[0]?.value }} - also, your call to getNewsDetail should be inside the subscribe and ideally that function call should pass the id. – MikeOne Sep 27 '21 at 20:57
  • @MikeOne {{ detailNews?.created[0]?.value }} returns the same "undefined" error. – Ricardo Castañeda Sep 27 '21 at 21:12
  • What exactly does {{ detailNews | json }} give you? – MikeOne Sep 27 '21 at 21:18
  • @MikeOne {{ detailNews | json }} prints the full object, with all its contents. And the console is free of errors. – Ricardo Castañeda Sep 28 '21 at 01:03
  • I have the same problem, {{myObject | json }} return : ` [ { "id": "Ob2MJ0F0J", "url": "https://cdn2.thecatapi.com/images/Ob2MJ0F0J.jpg", "width": 3024, "height": 3024 } ] ` but {{myObject.id}} return nothing and generate ctx.myObject is undefined. – Pipe Soto Sep 02 '22 at 06:59

0 Answers0