schaenk
schaenk

Reputation: 672

NativeScript & Angular2 - How to bind an object?

I'm trying to display data from a REST API. But, the UI is rendered before the data is loaded. So I'm getting a following error:

Cannot read property 'name' of undefined

How can I bind an object?

The component:

@Component({
    selector: 'foo-detail',
    templateUrl: 'foo.component.html',
    providers: [FooService],
})
export class FooDetailComponent implements OnInit {
    public foo:Foo;

    constructor(private fooService:FooService,
                private route:ActivatedRoute) {
    }

    ngOnInit() {
        this.route.params
            .map(params => params['id'])
            .subscribe(fooId => {
                this.fooService
                    .get(+fooId)
                    .subscribe(res => this.foo = res);
            });
    }
}

The service:

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

    get(fooId) {
        return this.http.get('http://api.foo.com/foos/' + fooId)
            .map(res => res.json())
            .map(foo => {
                return new Foo(foo.id, foo.name, foo.description);
            });
    }
}

The template:

<ActionBar [title]="foo.name"></ActionBar>
<GridLayout>
    <Label [text]="foo.description"></Label>
</GridLayout>

Upvotes: 1

Views: 252

Answers (1)

Stefan Svrkota
Stefan Svrkota

Reputation: 50633

You can use ngIf directive or safe navigation operator (?) (known also as Elvis operator) to "protect" your template:

ngIf directive

<div *ngIf="foo">
<ActionBar [title]="foo.name"></ActionBar>
<GridLayout>
    <Label [text]="foo.description"></Label>
</GridLayout>
</div>

Elvis operator

<ActionBar [title]="foo?.name"></ActionBar>
<GridLayout>
    <Label [text]="foo?.description"></Label>
</GridLayout>
</div>

I suggest reading official Angular 2 page about ngIf directive to understand how it works, as well as template syntax page about safe nagivation operator (?).

Upvotes: 3

Related Questions