2

I would like to get results array from atom.service into atom.component. I thought I could bring in results array into atom.component with source codes below (not presented whole codes). But I found I could not access this.atoms in atom.component from source codes below. The results array in atom.service.ts was created successfully. If anyone knows about how to get access to results array in the atom.component, could you give some guide about it?

atom.service.ts

getAtoms(private newConcept: string) {
    this.http.get('api/atoms.json')
    .map( (responseData) => {return responseData.json()})
    .subscribe( data => {   
        let results:Array<RAtom> = [];
        for (i = 0; i < data.result.length; i++) { 
            results.push(new RAtom(data.result[i].classType, data.result[i].ui));
        }
        return results;
    });
}

atom.component.ts

atoms: Array<RAtom>;

searchAtoms(newConcept: string) {
    if (newConcept) {
    this.atoms = this.service.getAtoms(newConcept);
    }
}

RAtom.ts

export class RAtom {
    classType: string;
    ui: string;

    constructor(classType: string, ui:string) {
      this.classType = classType;
      this.ui = ui;
    }
}
4
  • Subscribe in the component, not in the service. The Angular 2 docs are full of examples of this. Commented Nov 15, 2016 at 19:23
  • First, could I ask how they are different, I roughly understand but could I ask it? Commented Nov 15, 2016 at 19:28
  • I don't understand what you're trying to ask. Commented Nov 15, 2016 at 19:29
  • I forgot to say, thank you so much for your kind reply! Commented Nov 15, 2016 at 19:30

1 Answer 1

2

You can't get back from async execution to sync execution.

Instead of subscribing in getAtoms() let the caller subscribe, then he can pass a callback that gets called when the data arrives:

getAtoms(private newConcept: string) {
    return this.http.get('api/atoms.json')
    .map( (responseData) => {return responseData.json()})
    //.subscribe( data => {   
    .map( data => {    
        let results:Array<RAtom> = [];
        for (i = 0; i < data.result.length; i++) { 
            results.push(new RAtom(data.result[i].classType, data.result[i].ui));
        }
        return results;
    });
}
atoms: Array<RAtom>;

searchAtoms(newConcept: string) {
    if (newConcept) {
      this.service.getAtoms(newConcept)
      .subscribe(result => this.atoms = result;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Finally. Glad to hear. Sorry again for being so sloppy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.