Encountering [Object Object] within an angular2 app

https://i.stack.imgur.com/iceKH.pngI recently created an angular2 application using ngrx/effects for handling http calls. My reference point was an application on GitHub. However, I am facing an issue where the response from the HTTP call is not displaying properly on the screen; instead, it shows [object Object]. Below is a snippet of my code:

The HTML page linked to component.html

<div class="container">
<div class="left-container cf">
<mat-tab-group>
    <mat-tab label="Configuration">{{jsons}}</mat-tab>
    <mat-tab label="Captured Output">
    </mat-tab>
</mat-tab-group>
</div>
</div>

Component.ts

        export class ExperimentDetailsComponent implements OnInit {

      jsons: Observable<any>;
      isLoading: Observable<any>;

      constructor(
        private store: Store<fromStore.State>
      ) {
        this.isLoading = store.select(fromStore.getIsLoading);
        this.jsons = store.select(fromStore.getJson);
        console.log(this.jsons)
      }

      ngOnInit() {
        this.store.dispatch(new jsonAction.GetJson());
        // this.jsons = this.store.select(fromStore.getJson);
      }
    }

Effects.ts

        export class GetJsonEffects {

      @Effect() json$ = this.actions$.ofType(Act.GET_JSON)
        .map(toPayload)
        .withLatestFrom(this.store$)
        .mergeMap(([ payload, store ]) => {

          return this.http$
            .get(`http://localhost:4000/data/`)
            .map(data => {
              return new Act.GetJsonSuccess({ data: data })
            })
            .catch((error) => {
              return Observable.of(
                new Act.GetJsonFailed({ error: error })
              );
            })
        });


      constructor(
        private actions$: Actions,
        private http$: HttpClient,
        private store$: Store<fromStore.State>
      ) {}
    }

Answer №1

When using store.select(), the result is an observable which cannot be directly data bound.

You have two options:

Option 1: Use the async pipe to subscribe to the observable and extract the data for UI display, like this:

<mat-tab label="Configuration">{{jsons | async}}</mat-tab>

Option 2: Subscribe manually to the observable like below:

export class ExperimentDetailsComponent implements OnInit {

     jsonSubscription = store.select(fromStore.getJson)
          .subscribe(jsons => this.jsons = jsons);

    ngOnDestroy() {
      this.jsonSubscription.unsubscribe();
    }
      jsons: any;

     // ...
}

Additionally,

If using the Http service (from @angular/http module):

Make sure to call data.json() within the map() of your effect to return the extracted JSON from the Response object, as demonstrated here:

      return this.http$
        .get(`http://localhost:4000/data/`)
        .map(data => {
          return new Act.GetJsonSuccess({ data: data.json() })
        })

Lastly,

If utilizing the HttpClient service (from @angular/common/http module):

(Available in Angular v4.3+)

The need to explicitly call .json() is not required as it's automatically handled by HttpClient. You can specify the expected type of JSON by calling get<MyInterfaceName> as shown below:

      return this.http$
        .get<MyInterfaceName>(`http://localhost:4000/data/`)
        .map(data => {
          return new Act.GetJsonSuccess({ data: data.json() })
        })

The get<MyInterfaceName>() informs TypeScript about the JSON structure to enable intellisense and error checking at compile time.

For more information, refer to the HttpClient Documentation

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

How to retrieve the dimensions of an image for a specified CSS class with Selenium or PIL in Python

I am interested in using Python to determine the size of specific images. Is it possible to automate this process so that I can identify only images with certain classes? I am unfamiliar with PIL. Could I define the CSS class/name/id after specifying the U ...

What is the best way to prevent users from entering a zero in the first position of a text box using JavaScript

Although I am aware this may be a duplicate issue, the existing solution does not seem to work for me. The field should accept values like: valid - 123,33.00, 100,897,99, 8000 10334 9800,564,88.36 invalid - 001, 0 ...

Node.js server-side storage solutions for integration with Dojo

Currently, I am working on developing a new application. It is my first time creating a single-page AJAX application that solely relies on Restful stores. So far, I have written some code and executed simple queries using the GET method. To maintain organ ...

Is it possible to represent a recursive variable using CSS?

When it comes to the html structure: <body> <div> <div> <div> ... </div> </div> </div> </body> Is there a method to create recursive variables that utilize their parent's value: body ...

Having trouble getting the image to stack in the center above the text on mobile devices

When viewing the website on a desktop, everything appears correctly. However, there seems to be an issue with responsiveness on mobile and tablet devices. Specifically, I want to ensure that the image of team members stacks above their respective bio parag ...

Radio buttons have been concealed and are not visible

Tried the solutions recommended in a previous question about radio buttons not showing in Safari and Chrome, but unfortunately, it did not solve my problem. It seems like this issue is different from the one discussed in that question. The WordPress them ...

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

Is there a way to invoke an Angular2 function from within a Google Map infowindow?

I am currently working on integrating Google Maps using javascript in a project, and I'm facing a challenge. I want to call an Angular2 function inside an infowindow as shown in the code snippet below. Pay attention to the infoContent variable that co ...

Creating a color icon for StackExchange using HTML

I am currently working on building my personal website. I am looking to include a link to my Stack Exchange profile on my site using the Stack Exchange icon. However, the icons available in Font Awesome are grayscale and not colored like other icons such a ...

Merge web address when form is sent

I'm currently working on a search application using the Django framework and the Yelp API as my backend, which is functioning properly. However, I am facing some challenges with the frontend development, specifically integrating Leaflet.js. My search ...

The module 'AnotherModule' in a different file has unexpectedly imported a value 'Module in file'. Make sure to include a @NgModule annotation to resolve this issue

After struggling with this problem for the past four days, I've exhausted all resources on Stack Overflow and Google. Hopefully, someone here can provide some insight. I have two Angular 11 libraries - one core and the other called components. Compone ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

including a code snippet within a dropdown menu or embedding it in a clickable button

Hey there, my name is Wouter Sanders and I am currently learning to code! I recently finished creating a RAL color picker for a project I'm working on. The only issue I've run into is trying to embed the code in a menu or button so that it doesn ...

Angular and the challenges of connecting Facebook OAuth due to CORS problem

In my API, I have implemented OAuth login and callback methods for popular platforms such as Facebook, Google, and Twitter. The API is built using Express.js framework and it runs on port 3000. Meanwhile, I also have an Angular 2 application running on p ...

Shifting hues of dots within a grid according to the passing of time

As a newcomer to the world of coding, I have conceptualized an idea for a visually appealing clock. My goal is to visually represent the passage of time throughout the day. To achieve this, I have devised a grid system where each dot on the grid represents ...

Implementing a Collapse and Expand All feature within an Accordion Component

Hey there! I've been attempting to implement a Collapse All feature on my accordion but am having trouble figuring it out. The resource I've been referencing is this one. I've searched around and noticed that this accordion setup is a bit d ...

Using PHP encryption and decrypting with AES in Angular using Crypto-JS

I have successfully implemented encryption and decryption in PHP using aes-256-cbc. However, I am now facing a challenge in decrypting the same content in Angular 7. Encryption in php using aes-256-cbc by following method $this->data ="plaintext&qu ...

Integrating modules in Angular 2

Exploring the functionalities of Angularjs 2.0, I encountered an issue when attempting to inject a service into a class. Below is the code snippet that's causing trouble: import {Component, View, bootstrap, NgFor, HttpService, Promise} from 'ang ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

Creating a continuous loop animation with CSS hover state

This piece of code creates an interesting effect when the text is hovered over. The slight shakiness adds a cool touch to it. However, this effect only occurs when the mouse is moved slowly; if the mouse remains stationary, the hover style takes precedence ...