Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript / Angular2: Cast JSON to interface with Observable & JSONP

I'd like to cast my json-array to my interface which I've created and like to display it in the browser. I think there is probably something wrong with my interface but I can't figure it out... What do I need to change to get my code running?

Interface:

 export interface Video {
  id: number;
  name: string;
  description: string;
  createdAt: string;
}

app.ts

import {JSONP_PROVIDERS, Jsonp} from '@angular/http';
import {Observable} from '../../../node_modules/rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/share';
import {Video} from './networking/api';

    private videoData: Observable<Video[]>;
    ngOnInit() {
                this.displayNewstVideo(10);
            }

            private displayNewstVideo(count: number) {
                this.videoData = this.jsonp
                .get('localhost:8080/video/newst/' + count + '?jsonp=JSONP_CALLBACK')
                .map(res => (res.json() as Video[]));
                alert(this.videoData.count);
            }

app.html

<div class="container">
  <div class="video" style="font-family:sans-serif" *ngFor="#entry of videoData | async;  #i = index">
      <br *ngIf="i > 0" />
      <span class="title" style="font-size:1.2rem">
        <span>{{i + 1}}. </span>
        <a href={{entry.urlDesktop}}>{{entry.name}}</a>
      </span>
      <span> ({{entry.description}})</span>
      <div>Submitted at {{entry.createdAt * 1000 | date:"mediumTime"}}.</div>
    </div>

JSON

[{
id: 1,
name: "Some Name",
description: "BlaBla",
createdAt: "2016-05-04 13:30:01.0",
},
{
id: 2,
name: "Some Name",
description: "BlaBla",
createdAt: "2016-05-04 13:30:01.0",
}]

Edits

  1. I've checked if the request is correct in my network-tab in chrome and it is working as excepted: 200 OK --> Response ist also fine
  2. I edited my code as Thierry stated out and now it is finally showing the first object in my array :-)!! But I get following error now:

Uncaught EXCEPTION: Error in app/html/app.html:27:11 ORIGINAL EXCEPTION: RangeError: Provided date is not in valid range. ORIGINAL STACKTRACE: RangeError: Provided date is not in valid range. at boundformat (native) at Function.DateFormatter.format (http://localhost:3000/node_modules/@angular/common/src/facade/intl.js:100:26) at DatePipe.transform (http://localhost:3000/node_modules/@angular/common/src/pipes/date_pipe.js:25:37) at eval (http://localhost:3000/node_modules/@angular/core/src/linker/view_utils.js:188:22) at DebugAppView._View_AppComponent1.detectChangesInternal (AppComponent.template.js:377:148) at DebugAppView.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core/src/linker/view.js:200:14) at DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core/src/linker/view.js:289:44) at DebugAppView.AppView.detectContentChildrenChanges (http://localhost:3000/node_modules/@angular/core/src/linker/view.js:215:37) at DebugAppView._View_AppComponent0.detectChangesInternal (AppComponent.template.js:198:8) at DebugAppView.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core/src/linker/view.js:200:14) ERROR CONTEXT: [object Object]

like image 424
safari Avatar asked May 13 '16 14:05

safari


People also ask

How do I cast a JSON object to a TypeScript interface?

1) Add a constructor in your Typescript class that takes the json data as parameter. In that constructor you extend your json object with jQuery, like this: $. extend( this, jsonData) .

How should I parse a JSON string in TypeScript?

TS has a JavaScript runtime Typescript has a JavaScript runtime because it gets compiled to JS. This means JS objects which are built in as part of the language such as JSON , Object , and Math are also available in TS. Therefore we can just use the JSON. parse method to parse the JSON string.

How do I Stringify a JSON object in TypeScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

How do you get a specific value from a JSON object in TypeScript?

To parse a JSON string in TypeScript, you can use JSON. parse().


2 Answers

You could try the following instead:

this.videoData = this.jsonp
    .get('localhost:8080/video/newst/' + count +
                      '?jsonp=JSONP_CALLBACK')
            .map(res => <Video[]>res.json();

Edit

I think that your request doesn't return JSONP content but classical one (JSON). If so, you could try the following:

import { bootstrap }  from 'angular2/platform/browser';
import { Component } from 'angular2/core';
import { HTTP_PROVIDERS, Http } from 'angular2/http';
import "rxjs/add/operator/map";

@Component({
  selector: "app",
  templateUrl: "app.html",
  providers: [HTTP_PROVIDERS]
})
class App {
  private feedData: Observable<Video[]>;

  constructor(private http: Http) { }

  ngOnInit() {
    this.displayNewstVideo(10);
  }

  private displayNewstVideo(count: number) {
    this.videoData = this.http
      .get('localhost:8080/video/newst/' + count)
      .map(res => (res.json() as Video[]))
      .do(videoData => {
        console.log(videoData);
      });
  }
}

bootstrap(App);
like image 61
Thierry Templier Avatar answered Sep 21 '22 20:09

Thierry Templier


Try using a class instead of an interface, so in this case video.model.ts would be:

export class Video {
  constructor(
    public id: number,
    public name: string,
    public description: string,
    public createdAt: string){}
}
like image 30
wolfhoundjesse Avatar answered Sep 21 '22 20:09

wolfhoundjesse