Unable to display object property on screen after printing Angular 2 array on console

I have written a method in my service:

getPost(nid: string): Observable<Post[]>{
    let url = "http://test.co.uk/api/v1/basic/" + nid;
    return this.http.get(url,  {headers: this.headers}).map(res => res.json() as Post).catch(err => {
      return Observable.throw(err);
    });
  }

Here is the structure of my component class:

export class PostDetailComponent implements OnInit {
  posts: Post[] = [];
  post: Post = new Post();
  constructor(
private route: ActivatedRoute,
private postService: PostService
) { }
  ngOnInit() {

    this.route.params.switchMap((params: Params) => {
      let nid = params ['nid'];
      return this.postService.getPost(nid);  }).subscribe(res => {
      console.log(res)
      this.post = res as Post;
    }, err =>{
      console.log(err);
  });

  }

}

This is the JSON feed data (containing one object in the array):

  [  
   {  
      "nid":"3",
      "title":"When Unity meets Vuforia",
      "body":"<p>Unless you have been living under a rock in the past 7 - ...",
      "uid":"admin",
      "path":"\/node\/3",
      "field_article_image":"http:\/\/test.co.uk\/sites\/default\/files\/when-unity-meets-vuforia_0.jpg?itok=BGYaotay"
   }
]

When I try to display {{post}}, it shows as [object Object] on the screen.

Displaying {{post | json}} shows the raw JSON feed data.

However, trying to show {{post.title}} or {{post?.title}} does not display anything.

The class Post has the following structure:

export class Post{
  constructor(

public nid?: string,
public title?: string,
public body?: string
public image?: string
  ){
  }
}

Any suggestions on how to solve this issue?

Answer №1

When dealing with arrays and objects, be careful not to assign an entire array to a single object. Make sure to copy the first element of the array into the designated variable.

this.post = res[0] as Post

It's important to note that assigning a raw object to a class instance can lead to issues. For instance, the this.post.constructor may not exist and

this.post instanceof Post == false
.

An alternative approach could be using Object.assign(this.post, res[0]), but be cautious about existing properties that may need to be cleared if not always present.

Personally, I recommend defining object shapes as interfaces instead. By using interfaces, you can avoid runtime errors caused by incomplete type information compared to using classes for static type checks during compilation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executable program contained within npm bundle

I am working on creating an npm package that can be executed as a command from the shell. I have a package.json { "name": "myapp", "version": "0.0.6", "dependencies": { "async": "", "watch": "", "node-promise": "", "rmdir": "", " ...

Angular 4: Unidirectional data flow from View to Component

Struggling to secure user credentials in my Angular form due to 2-way data binding displaying encrypted values within the component. Here's the code snippet: <form> <div class="input-group"> <span class="input-group-a ...

What could be causing the data inside the component to not display properly?

Consider this scenario where we have a component with input data: @Component({ selector: 'app-mail-list', templateUrl: './mail-list.component.html', styleUrls: ['./mail-list.component.scss']}); export class Ma ...

Accessing RESTful data using an Angular service

I am currently following a tutorial on building a RESTful API using the MEAN stack from scotch.io. I have been able to successfully set up my API to return JSON data and now I am looking to test it out. Should I try accessing the API through the browser a ...

Display an image in a pop-up when hovering over it briefly

When you run the code snippet and hover over "Hover here", a picture of grumpy cat will appear, but the image flashes on and off repeatedly: To see the image consistently, you may need to move your cursor away from "Hover here" and hover over it again. ...

Avoiding content resizing when using a drawer in Material UI

My project features a drawer that expands, but I am encountering an issue where the content inside the drawer resizes when expanded. However, this is not the desired outcome. I want the expanded drawer to overlay the content without resizing it. How can I ...

The 'otherwise' controller in AngularJS does not execute when the resolution in another controller has not been successful

Imagine having routes set up in the configuration: $routeProvider .when('/person/:person_id', { controller: 'person', templateUrl: 'partials/person.html', resolve: { data: ['api', '$route', ...

Retrieve the updated value of an item in a knockout observable array during a change event

Currently, I am utilizing knockout.js to create an editable table and I am attempting to trigger a validation function whenever the value of an input field within the table is modified. I have experimented with utilizing an editable computed observable as ...

How do you switch selection to "hold" mode using Javascript?

In my Markdown preview area, clicking on text will cause the preview area to switch to a markdown source editor automatically, with the cursor jumping to the position corresponding to where it was clicked. function onMouseDown(e) { const range = documen ...

Whenever I click on <a href="whatever.aspx"></a>, I would like the page to be displayed within the current page

This is the code I am working with: <asp:DataList ID="dlGallery" runat="server" RepeatLayout="Flow" Width="100%" CellPadding="4" ForeColor="#333333"> <AlternatingItemStyle BackColor="White" ForeColor="#284775" /> <FooterStyle BackColor ...

Tips for verifying the compatibility of elements as parent or child components

Is it possible in JavaScript to verify if an HTML element can be a child of another element? For instance: Can an unordered list (<ul>) contain a list item (<li>) as a valid child element? - Yes Can an unordered list (<ul>) contain ano ...

Function for Duplicating jQuery Events

I'm currently facing an issue where every time the browser is resized, a function is triggered. This function can turn a side panel into an accordion if the screen width meets certain criteria, or it can just display as an open side panel on larger sc ...

The Art of Determining the Text's Baseline

My goal is to create a test that determines whether the text rendered inside an <input> has the same baseline as a label: To achieve this, I want to calculate the baseline of the rendered text in each element and compare their values. Is it possible ...

Some browsers are experiencing issues with Javascript functionality

My JavaScript code is functioning perfectly on my development machine in Chrome, Firefox, and Safari. However, when others test it on their browsers, the value update does not work at all. Can anyone suggest how I can replicate this issue locally? Browser ...

Tips for iterating through an associative array/object within a MongoDB schema instantiation using mongoose without the need to specify schema configuration parameters

I've been searching on Google for hours without finding a clear answer. Perhaps I need to adjust my search terms? Here's my question: I'm a beginner with MongoDB and I'm trying to modify the values of a schema instance before saving it ...

Exploring methods to broaden the functionality of components through inheritance

My goal is to develop extensions for existing Angular 2 components without having to completely rewrite them. I want any changes made to the base component to also automatically apply to its derived components. To illustrate my point, consider the followi ...

What is the best way to locate a user-provided string within word boundaries using JavaScript regex?

Employing JavaScript, I am currently searching a body of text. Users are given the option to input any string they desire, and then I aim to search for that specific string, ensuring it is considered a "whole word" located between boundaries. All I need i ...

Tips for effectively implementing an Ajax request with JavaScript when the page loads

I have been developing a shopping cart application that utilizes local storage to store the items added by users. The challenge I'm currently facing is populating the page with the user's cart items stored in local storage when they navigate away ...

Finding repeating elements in an array of objects

Is there a way to identify duplicates in an array based on type, name, and size, increment the amount, and then remove the duplicate entries? [ { "name": "Pizza with pepper", "imageUrl": "...", ...

What steps should I take to resolve the textarea border bottom CSS effect?

My simple border bottom animation is working fine with a basic input element, but it's not functioning properly when used with a textarea. (If using JavaScript is necessary for a solution, please provide guidance) How can I adjust the height of a te ...