简体   繁体   English

如何访问从服务中获取的组件中的对象?

[英]how to access objects gotten from service in the component?

When I tried to access atoms using 'this.atoms' in the searchAtoms, it returns "TypeError: Cannot read property 'length' of undefined". 当我尝试在searchAtoms中使用“ this.atoms”访问原子时,它返回“ TypeError:无法读取未定义的属性'length'”。 I am thinking atoms are all set because *ngFor is working well. 我认为原子已经设置好了,因为* ngFor运作良好。 There is some hidden logic behind subscribe? 订阅背后有一些隐藏的逻辑吗? If someone knows about this, could you give some clues? 如果有人知道这一点,您能提供一些线索吗? And, also another question, when I defined getAtoms method with a parameter, atom name value gotten from input field in the atom.service.ts like this.service.getAtoms(newAtom). 还有另一个问题,当我使用参数定义getAtoms方法时,原子名称值是从atom.service.ts的输入字段中获得的,就像this.service.getAtoms(newAtom)一样。 But I get "A parameter proerty is only allowed in a constructor implementation". 但是我得到“仅在构造函数实现中允许使用参数属性”。 I think I can't use this way. 我想我不能用这种方式。 Could you anybody recommend a desirable way for this? 有人可以为此推荐一个理想的方法吗?

app.component.ts app.component.ts

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';
import {AtomService} from './service/atom.service';
import {Atom} from './datatype/Atom';

@Component({
    selector: 'my-app',
    template: `<br>
    <input #atomname value='atom1'>
    <button (click)=searchAtoms(atomname.value)>Search Atoms</button>  
    <br><br>
    <ul>
        <li *ngFor="#atom of atoms">
            {{atom.id}} - {{atom.name}}
        </li>
    </ul>`,
    providers: [ConceptService]
})


export class AppComponent {

    atoms: Array<Atom>;

    constructor(private service : AtomService) {

    }

    searchAtoms(newAtom: string) {
        console.log("searchAtoms\t" + newAtom);
        if (newAtom) {
            this.service.getAtoms(newAtom).subscribe(data => this.atoms = data);
            console.log(this.atoms.length);
        }
    }
}

atom.service.ts 原子服务

import { Injectable }     from 'angular2/core';
import { Http, Response, URLSearchParams, Headers } from 'angular2/http';
import 'rxjs/add/operator/map';
import {Atom} from '../datatype/Atom';

@Injectable()
export class ConceptService {

  constructor(private http: Http) {
    this.http = http;
  }

  getAtoms(private newAtom: string) {
    return this.http.get('api/atoms.js')
    .map( (responseData) => {return responseData.json()})
    .map( data => {
        let results:Array<Atom> = [];
        for (var i = 0; i < data.result.length; i++) {
            results.push(new Atom(data.result[i].id, data.result[i].name));
        }
        return results;
    });
  }
}

The Http service returns an Observable and you subscribe to it. Http服务返回一个Observable ,您订阅了它。 This is an asynchronous operation but you are trying to access the data before it arrives from the server. 这是一个异步操作,但是您试图在数据从服务器到达之前对其进行访问。 If you move your console.log inside of your subscribe callback it will work. 如果将console.log移动到您的subscribe回调中,它将起作用。

this.service.getAtoms(newAtom).subscribe(data => {
  this.atoms = data;
  console.log(this.atoms.length);
});

For your second question you just need to drop the private keyword. 对于第二个问题,您只需要删除private关键字即可。

getAtoms(newAtom: string) { }

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

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