Selecting keys of an object in Angular 2

Attempting to fetch data from an API using key selection but encountering retrieval issues.

File: app/app.component.ts

import {Component, OnInit} from 'angular2/core';
import {Http} from 'angular2/http';
import {httpServiceClass} from './service';
import {HTTP_PROVIDERS} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Api} from './api';

@Component({
selector: 'my-app',
templateUrl: 'mytemplate.html',
providers:[httpServiceClass, HTTP_PROVIDERS]
 })

export class AppComponent implements OnInit{
 private api:Api[];
 constructor(private getservice:httpServiceClass){}

 ngOnInit(){
 this.getservice.httprequest()
   .subscribe(data => this.api = data );
  }

}

Service file: app/app.service.ts

import {Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
import {Api} from './api';

@Injectable()
export class httpServiceClass{
    constructor(private http: Http){}

    httprequest(): Observable<Api[]>{
        return this.http.get('http://date.jsontest.com')
            .map(response => response.json());
    }
}

API interface in api.ts

export interface Api{
  time:string;
  date:string;
}

mytemplate.html content:

<h1 >HTTP : {{api|json}}</h1>

Returns the following JSON data:

{"time": "01:52:41 PM", "milliseconds_since_epoch": 1472910761126, "date": "09-03-2016"}

Attempted to select by key:

<h1 >HTTP : {{api.time}}</h1>

Error message in console:

EXCEPTION: Cannot find a differ supporting object '[object Object]' in [api in AppComponent@0:4]

Answer №1

In the world of JavaScript, an interface at runtime doesn't hold much significance. You might want to consider converting your interface to a class to see if that resolves the issue. Be sure to refactor the code as needed afterwards.

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

Generate a basic collection of strings from an object

Looking at this object structure Names = [ { group: 'BII', categories: null }, { group: 'GVL', categories: [] } ]; I ...

Execute different commands based on operating system using NPM conditional script for Windows and Mac

Scenario: I am currently configuring a prepublishOnly hook in NPM. This hook is designed to remove the "lib" folder, transpile the typescript source files into a new lib folder, and then execute the tests. The issue at hand: There are two individuals re ...

How can data be passed from a directive to a controller in Angular?

I am currently working on implementing a directive pagination feature and I need to pass the current page number from the directive to a controller in order to run a specific function with this argument. However, I keep getting an 'undefined' err ...

Not quite sure why the commitment is not being fulfilled

Before in my angular controller, I had: var getResponse = function () { $http.post("api/screen/", { Key: 'banana', value: null }) .then(onComplete, onError); }; var onError = function (reason) { $scope.error = "F ...

Issue with directive in AngularJS: When trying to access scope.data, it appears

Initially, I came across the API address in this discussion: Laravel 4 and Angular JS and Twitter Bootstrap 3 Pagination Now, I am delving into this topic, and my script snippet goes like this: var app = angular.module('category', [ &ap ...

Using AngularJS to bind a dictionary to an ng-repeat function

Hello everyone! I have a dictionary with keys and lists of objects returned from my controller. I want to bind this data to a table or another element using the ng-repeat directive. This is how the data looks when returned from the controller: https://i.s ...

Tips for eliminating unicode characters from Graphql error messages

In my resolver, I have implemented a try and catch block where the catch section is as follows: catch (err: any) { LOG.error("Failed to get location with ID: " + args.id); LOG.error(err); throw new Error(err); ...

Implementing a search filter for special characters in AngularJS

Looking to filter an array of players by their names, but facing a challenge with special characters in the names. Found a code snippet on Google that looks like this: $scope.modelFilterNormalized = function(){ if($scope.modelFilter) return $sco ...

Eliminate the unnecessary code repetition in my functions using Typescript

I have 2 specific functions that manipulate arrays within an object. Instead of repeating the same code for each array, I am looking for a way to create reusable functions. Currently, my functions look like this: setLists(): void { if (this.product.ord ...

The function $scope.myFunction has not been declared

https://i.sstatic.net/rVikL.pngHere's some AngularJS code that I'm working with: The code successfully displays an alert saying "inside controller", but then it encounters an error and doesn't display any further alerts. Instead, it stops a ...

What is the best way to integrate a JSON response obtained from $http.get in Angular?

When retrieving a JSON using $http.get, I am facing compatibility issues with Angular. To make it compatible, I have to convert it like this: $http.get('/api/v1.0/plans'). success(function(data) { var plans = []; for(var prop ...

What is the reason behind Typescript executing the abstract class before anything else?

I'm currently facing a challenge solving an abstract class problem with Typescript. Let me explain what I am trying to accomplish. There is a class named Sword that extends Weapon. Each Weapon must have certain properties like the damage, but since e ...

What benefits does using the "Controller as" syntax provide in Angular?

Can you explain the benefits of utilizing the "Controller as" syntax in Angular? Is it simply to give a controller an alias, or are there deeper technical implications at play? As someone who is new to Angular, I am eager to learn more about this unique s ...

Method for detecting changes in an AngularUI select2 dropdown

Is there a way to achieve something like the following: <select ui-select2 multiple="true" on-change="onChange()" data-ng-model="select2Model"></select> In my controller, I have the onChange(select2OnChangeData) function implemented. I at ...

Having difficulties accessing the properties of a dynamically created JSON object with ng-repeat functionality

Within an ng-repeat loop, I have implemented a radio button that assigns the entire person object to a scope variable as shown below: <li ng-repeat="person in people"> <label>{{person.name}} <input type="radio" ng-model="$parent.s ...

What is the solution to the error message stating that the property 'pipe' is not found on the OperatorFunction type?

I implemented the code based on RxJS 6 documentation while working with angular 5, RxJS 6 and angularfire2 rc.10. However, I encountered the following error: [ts] property 'pipe' does not exist on type 'OperatorFunction<{}, [{}, user, str ...

Combining 2 lists in Angular Firebase: A Simple Guide

I have been searching for a solution for the past 2 hours, but unfortunately haven't found one yet. Although I have experience working with both SQL and NoSQL databases, this particular issue is new to me. My problem is quite straightforward: I have t ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

HTML Code for Tracking Facebook Friends' Likes on a Page

I am looking to show the number of friends who have liked a page in HTML. Can someone please guide me on this? I am aware that we can get the page likes using a simple URL, but I specifically want to know how to retrieve the count of friends who liked a ...

Define an object type in Typescript that includes both specified properties and an unlimited number of unspecified properties

I'm attempting to create a custom data type using the code below, but it's not working: type CustomDataType { [key: string]: CustomDataType; isValid: boolean; errors?: string[]; } My goal is to have a CustomDataType with an isValid propert ...