0

enter image description here

The FeaturedCategories model

export class FeaturedCategories {
    categories: Array<{ id: number, title: string, graphic: string, categorycards: Array<{}> }>;
}

Also tried this:

export class FeaturedCategories {
    id: number;
    title: string;
    graphic: string;
    categorycards: Object[];
}

The Component

import { Component, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { ApiService } from '../shared/services/api.service';
import { FeaturedCategories } from '../shared/models/home/featuredcategories';

@Component({
    changeDetection: ChangeDetectionStrategy.Default,
    encapsulation: ViewEncapsulation.Emulated,
    selector: 'home',
    styleUrls: [ './home.component.css' ],
    templateUrl: './home.component.html'
})
export class HomeComponent {
    testFeaturedCategories: Array<FeaturedCategories>;

    constructor(private api: ApiService) {
        // we need the data synchronously for the client to set the server response
        // we create another method so we have more control for testing
        this.universalInit();
    }

    universalInit() {
        console.log('universalInit...')
        this.api.getFeatured()
            .subscribe(categories => {
                console.log('categories', categories);
                this.testFeaturedCategories = categories
            });
    }
}

This will work: testFeaturedCategories: Array<{}>;

However I'm trying to use TypeScript to let my App know what type of model to expect.

This causes the error above: testFeaturedCategories: FeaturedCategories.categories;

And if I just try this: testFeaturedCategories: FeaturedCategories;

I get a type [{}] is not assignable error.

enter image description here

enter image description here


UPDATE

So I noticed that when I commented out all the keys in my FeaturedCategories model finally the error goes away and

featuredCategories: FeaturedCategories[]; will work.

However now this is just an empty object without keys to expect :(

export class FeaturedCategories {
    // id: number;
    // title: string;
    // graphic: string;
    // categorycards: Object[];
}
6
  • It says it's undefined: <= well yeah, you broke on the line before you set a value. Also do not call service code chained from the constructor. Use ngInit for that. Commented Mar 7, 2017 at 19:36
  • I'm using Angular-universal to serve up static pages with Node. I assumed the universalInit replaces ngInit? Also featureCategories is typed to FeaturedCategories my model, so it should have something by now. I'm trying to re-create this in a plnkr atm. Commented Mar 7, 2017 at 19:38
  • You call it from the constructor, that is wrong. Call it from ngInit or there might be an interface you need to implement that defines universalInit. Eitherway do not call it from the constructor. Commented Mar 7, 2017 at 19:40
  • Also I can't find any method named universalInit or interface that defines such a method in the repo. Commented Mar 7, 2017 at 19:45
  • Ok I re-created a plnkr here that is close: plnkr.co/edit/gwa3NWArtWK0wjf2jr2h?p=preview I can't see any Typescript errors in plnkr, but I put in 2 console.logs Commented Mar 7, 2017 at 19:52

2 Answers 2

1

this is working fine for me.

export class MyComponent {
 categories: FeaturedCategories[] = [{
  id: 1,
  title: "",
  graphic: "",
  categorycards: [{}]
 }];
}

export class FeaturedCategories{
 id: number;
 title: string;
 graphic: string;
 categorycards: Object[];
}
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks, but getting the same error type [{}] is not assignable to type FeaturedCategories
Can you console the response and add to question ? Probably you are receiving empty object in response as error says it only have assignment issue.
Added! This is when using the model design you wrote.
Weird! those objects have all these properties { id: number, title: string, graphic: string, categorycards: Array<{}> } ? let me check locally as well with same model
Still the same problem :( I'll have to see if I can mini-mize my app and remake it in Plnkr and will add the link here. Another thing tho, FeaturedCategories is suppose to return an Array, not an Object. That's why originally I had another key in there categories. Possible issue there?
|
0

My problem was trying to type my Array, instead of just using the Typed objects that exist in the larger Array.

Also had a problem in my service, originally I had this:

/**
 * Get featured categories data for homepage
 * /wiki
 */
getFeatured(): Observable<[{}]> {
    return this.http.get(`${this.getFeaturedUrl}/home`)
    // .do(res => console.log('getFeatured res', res.json()))
    .map(res => res.json())
    .catch(this.handleError);
}

I did not need or could even use a type for my larger Categories array, what I needed was a smaller type for the exact Objects that exist in that larger Array:

export class FeaturedCategory {
    id?: number;
    type: string;
    title: string;
    graphic?: string;
    video?: string;
    categorycards: Array<{}>;
}

So now with the correct Type of Objects inside my Array I added it to the service:

getFeatured(): Observable<[FeaturedCategory]> {
    return this.http.get(`${this.getFeaturedUrl}/home`)
    .map(res => res.json())
    .catch(this.handleError);
}

enter image description here

Now back in my Component I imported the single Typed Object

import { FeaturedCategory } from '../shared/models/home/featuredcategory';

Then typed the variable:

featuredCategories: Array<FeaturedCategory>;

And finally in ngOnInit

ngOnInit() {
    this.api.getFeatured()
        .subscribe(categories => {
            console.log('categories', categories);
            this.featuredCategories = categories;
        });
}

No more errors :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.