访问Angular2对象?

时间:2016-10-05 00:21:19

标签: angular

我想保存并访问Angular2对象但我未定义为值。我得到一个对象,但这不可访问,如数组。我该怎么做数组?

Node.js api.js

api.get('/getData', function(req, res){
  res.send({name:'test'})
});

Dataservice PassProfileDataService.ts

import {Component, Injectable} from '@angular/core'
import { Http} from "@angular/http";


@Injectable()
export class PassProfileDataService {

constructor(private http: Http) {}

getItems(){
    return this.http.get('/api/getData').map((res:any) => res);
}
}

使用该服务的组件

import {Component, Input, OnInit} from '@angular/core';
import {PassProfileDataService} from '../common/PassProfileDataService';


@Component({
styleUrls:['/assets/css/bootstrap.css', '/assets/css/profile.css'],
    selector: "profile",
    templateUrl: `client/components/profile/profile.component.html`

})

export class ProfileComponent implements OnInit {

items:any;

constructor(private _sharedService: PassProfileDataService){}

ngOnInit(){
    this.items = this._sharedService.getItems();
    console.log(this.items + ' test');
}

}

视图组件profile.component.html

<div *ngFor="let i of items">
{{i.name}} 
</div>

我得到以下异常:

core.umd.js:3462 EXCEPTION:无法找到不同的支持对象&#39; [object Object]&#39;类型&#39;对象&#39;。 NgFor仅支持绑定到Iterables,例如Arrays。

3 个答案:

答案 0 :(得分:2)

this.items.subscribe(...)是异步的,意味着它现在不会运行该代码。 this.items是一个Observable,简而言之就是当最终发生某些事情时,您会收到通知,并且&#34;观察&#34;事件或一系列事件发生时。在这种情况下,它看起来像是对getUserWishList()的响应的承诺。我写了很多看起来像这样的代码。

如果一切按计划进行,最终订阅可观察量将会触发,this.data将等于value,但我可以保证,当您尝试时,它不会在下一行发生并打印出来。

this.items.subscribe(value => console.log(value));有效,因为当事件最终起作用时,你有价值并可以打印出来。

this.items.subscribe(value => this.data = value);也有效。最终。它只是像你期待的那样快速地完成。

您可以稍微修改一下代码:

this.items.subscribe(value => {
  this.data = value;
  console.log(this.data);
});

您将在控制台中看到该值,如果有任何内容绑定到this.data,它还应该反映视图中的数据。这可能有点棘手,如果在Observable回来之前data.name没有保留任何内容,如果您尝试在视图中绑定this.data,则会收到错误。

答案 1 :(得分:1)

这是因为框架的异步行为。代码不会等待您的服务返回。它进入下一个陈述,并在那个时间点,&#34;数据&#34;未定义。更改以下代码:

this.items.subscribe(value => this.data = value);
console.log(this.data);

为:

this.items.subscribe(value => {
this.data = value;
console.log(this.data);
});

你看到了区别吗?我将console.log移至success服务电话块。这是使代码以同步方式运行的一种快速方法。当您需要Observable.forkJoin时,还有其他方法可以在代码中引入同步行为。希望你明白了。

答案 2 :(得分:0)

TypeScript允许您在定义函数时使用箭头符号访问外部函数作用域,方法是将参数包装在括号中。

要保存数据的价值,只需使用:

this.items.subscribe((value) => this.data = value);

要保存数据,然后在数据到达后立即输出,您可以使用:

this.items.subscribe((value) => {
    this.data = value;
    console.log(this.data);
});