Muirik Muirik -4 years ago 121
Javascript Question

Rendering a Number to the View using String Interpolation in Angular 2

I am querying our mongoDB API endpoint in order to obtain the value that represents the total number of records. If I try that API endpoint call directly in Postman, I get the number "1227" returned (a number, not a string). Now I am trying to get that value rendered to the view in my Angular app. I am using an observable to get the value. In my service I have this:

getStaffCount() {
return this._http.get(``)
.map((response: Response) => response.json())

Then, in my component I am subscribing and saving the result of this observable in a variable like this:

const counts = this.staffService.getStaffCount()
.subscribe(resRecordsData => this.records = resRecordsData,
responseRecordsError => this.errorMsg = responseRecordsError);

Then, in my view I am using string interpolation, like this:


This produces the following error:

EXCEPTION: Error trying to diff '1227'

How can I resolve this error? Is this a matter of needing to convert the number to a string before rendering to the screen? Or is there something else I can do to handle it? Perhaps Angular has a way I can structure the value so that it's evaluated and rendered on the fly in the view?

Answer Source

It's because counts is a Subscription object, not a number, which is what subscribe() returns.

The result from the API (via the observable) is stored right now in this.records, which is what you should put into the string interpolation in your template.

If that doesn't work, you'll need to inspect resRecordsData in your browser's debugger and see how exactly the JSON result is formatted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download