NativeScript& Angular2 - 如何绑定对象?

时间:2016-10-23 20:31:00

标签: angular nativescript angular2-nativescript

我正在尝试显示REST API中的数据。但是,在加载数据之前呈现UI。所以我收到了以下错误:

  

无法读取未定义的属性“名称”

如何绑定对象?

组件:

@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);
            });
    }
}

服务:

@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);
            });
    }
}

模板:

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

1 个答案:

答案 0 :(得分:3)

您可以使用ngIf指令或安全导航操作符(?)(也称为Elvis运算符)来“保护”您的模板:

ngIf指令

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

猫王运营商

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

我建议您阅读official Angular 2 page about ngIf directive以了解其工作原理以及template syntax page about safe nagivation operator (?)