简体   繁体   English

访问Angular2对象?

[英]Access Angular2 object?

I want to save and access to the Angular2 object but I am getting undefined as value. 我想保存并访问Angular2对象,但未定义为值。 I am getting a object but this not accessible such as array. 我正在获取一个对象,但是无法访问它,例如数组。 How can I do it as array? 我该如何做阵列?

Node.js api.js Node.js api.js

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

Dataservice PassProfileDataService.ts 数据服务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);
}
}

Component which consumes the service 使用服务的组件

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

} }

The view component profile.component.html 视图组件profile.component.html

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

I am getting following Exception: 我正在关注以下异常:

core.umd.js:3462 EXCEPTION: Cannot find a differ supporting object '[object Object]' of type 'object'. core.umd.js:3462例外:无法找到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor only supports binding to Iterables such as Arrays. NgFor仅支持绑定到Iterables,例如数组。

this.items.subscribe(...) is asynchronous meaning that it won't run that code right now. this.items.subscribe(...)是异步的,这意味着它不会立即运行该代码。 this.items is an Observable which in short means that when something happens eventually, you can be notified and "Observe" the event or series of events when they happen. this.items是一个Observable ,简而言之意味着,当某件事最终发生时,您可以得到通知,并在事件发生时“观察”该事件或一系列事件。 In this case it looks like it works a lot like a promise for the response to getUserWishList() . 在这种情况下,它看起来很像对getUserWishList()的响应的承诺。 I've written a lot of code that looks just like this. 我写了很多看起来像这样的代码。

If all goes according to plan, eventually the subscription to the observable will fire and this.data will equal value but I can guarantee that it won't happen by the next line when you try and print it out. 如果一切都按计划进行,最终将触发对observable的订阅,并且this.data将等于value但我可以保证在尝试打印时不会在下一行发生。

this.items.subscribe(value => console.log(value)); works because when the event eventually does fire you have value and can print it. 之所以起作用,是因为当事件最终触发时,您就具有了价值并可以打印出来。

this.items.subscribe(value => this.data = value); also works. 也可以。 Eventually. 最终。 It just won't be done as fast as you're expecting. 它只是不会以您期望的速度完成。

You could modify your code a little to be both: 您可以稍稍修改一下代码,使其既可以:

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

You'll see the value in the console and if anything is bound to this.data it should also reflect the data in the view. 您将在控制台中看到该值,并且如果此this.data绑定了任何内容,它也应该在视图中反映该数据。 This can be a little tricky though, you'll get an error if you try to bind data.name in the view if this.data doesn't hold anything before the Observable comes back. 但是,这可能会有些棘手,如果在Observable返回之前,如果this.data不包含任何内容,则尝试在视图中绑定data.name会出错。

This is because of async behavior of framework. 这是由于框架的异步行为。 Code does not wait for your service to return. 代码不等待您的服务返回。 It proceeds to next statement and at that point of time, "data" is undefined. 它进行到下一条语句,并且在那个时间点,“数据”是未定义的。 Change following of your code: 更改以下代码:

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

to: 至:

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

Do you see the difference? 你看得到差别吗? I moved console.log to success block of service call. 我将console.log移至success的服务呼叫区。 This is one quick way of making your code run in synchronus manner. 这是使代码以同步方式运行的一种快速方法。 There are other ways as well to bring synchronus behavior in your code when you need ie Observable.forkJoin . 还有其他方法可以在需要时在代码中引入同步行为,即Observable.forkJoin Hope you got the idea. 希望你有主意。

TypeScript allows you to access the outer function scope when defining a function, using arrow notation, by wrapping the parameters in parentheses. TypeScript允许您在定义函数时使用箭头符号通过将参数包装在括号中来访问外部函数范围。

To save the value of data simply use: 要保存数据的价值,只需使用:

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

And to save the data and then output it as soon as it arrives you can use: 要保存数据并在数据到达后立即输出,可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM