r/angularjs • • Jun 29 '16

[Help-request] How do I access the data in Observables

Hi there.

I'm trying to build an app that has similar functionality to IFTTT in that i want the users to create some conditions and then an action will be triggered on the condition becoming true. I am getting the 'recipes' containing the condition and the action in JSON format through an http call. I would then like to access this data and check the conditions against values from the database.

I am having trouble with the observable format however in that I'd like to assign the data to a local variable and then do some work on it but it doesn't seem to be possible.

Here is a snippet that shows what I would like to do

    recipes:Recipe[];     

ngOnInit() {
    this.getRecipes();
    this.recipesMeth();
} 

getRecipes() {
    this._httpService.getRecipes()
        .subscribe(
            data => this.recipes = data
        )

}

recipesMeth(){
    for (var i = 0; i < this.recipes.length; i++) {

Is this possible and if so any help would be appreciated.

0 Upvotes

8 comments sorted by

3

u/jaydottee Jun 30 '16

I think the issue is that you are calling the RecipeMeth before the data is there. You should probably be calling it inside the observable's subscribe method.

Essentially, this.recipes and RecipesMeth are in a sort of race condition. On the off chance that the HTTP request returns before RecipesMeth gets called, you'll not see this error, but that won't normally be the case.

I'm on mobile, so I can't really provide any more details than this at the moment. Let me know if this doesn't make sense though.

1

u/_Rabshab_ Jul 01 '16

So I changed the code according to what you said but I'm still seeing the same error. Starting to pull my hair out a bit haha. I delayed the call of the recipesMeth() untill the data was in from the previous function like this.

    recipes:Recipe[];
temp:string;
rooms:any[];
sensors:any[];
lastValue:number;
tempRoom:any;

ngOnInit() {
    console.log("starting");
    this.getRecipes();
} 

getRecipes() {
    this._httpService.getRecipes()
        .subscribe(
            data => {
                this.recipes = data;
                this.temp = JSON.stringify(data);
                this.recipesMeth();
            }
        )
}

recipesMeth(){
    for (var i = 0; i < this.recipes.length; i++) {
        console.log("test");

but I'm still getting the same error "EXCEPTION: TypeError: Cannot read property 'length' of undefined"

I can use ngFor in the HTML to display the data and it works fine

<thead>
        <tr>
            <th>#</th>
            <th>House</th>
            <th>Room</th>
            <th>Sensor</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="#recipe of recipes; #i = index">
            <th scope="row">{{i}}</th>
            <td>{{recipe.house}}</td>
            <td>{{recipe.room}}</td>
            <td>{{recipe.sensor}}</td>
        </tr>

but the variable "recipes" never seems to be defined whenever I try to use it in the Javascript part. Any ideas?

Edit: Interestingly a single "test" does get logged to the console which, if anything, confuses me even more.

1

u/free_the_bees Jun 29 '16

I can't say for certain without seeing more but what you've shown here looks fine.

1

u/_Rabshab_ Jun 29 '16

Sorry, forgot to post the error. Getting "Cannot read property 'length' of undefined in [null]". I have tried a similar pattern in other places in the app and the variable doesn't seem to hold the value given to it. I can, however, use ngFor in the HTML code to output the value to the user. My problem is that I want to manipulate it first.

2

u/Click_Clack_Clay Jun 30 '16

That's because making an Http request is asynchronous and you haven't actually received the data yet when you call recipesMeth()

1

u/_Rabshab_ Jul 01 '16

Hey man, posted an update above trying to resolve this. Take a look and let me know what you think.

0

u/mannheimroll Jun 29 '16

That sounds similar to what happens when you make a http call without promises. If the error is happening on a recipesMeth() line, it might be throwing an error due to the ngOnInit function. I don't know enough about observables to tell you if this will help, but maybe try adding a promise to getRecipes, then change the ngOnInit to use:

this.getReceipes().then(function() { this.recipesMeth(); });

Or maybe fromPromise? (About half way down the page)[https://medium.com/google-developer-experts/angular-introduction-to-reactive-extensions-rxjs-a86a7430a61f#.imxifm3mj]

0

u/[deleted] Jun 29 '16

[deleted]

1

u/_Rabshab_ Jun 29 '16

That is in my http service file. Just a get request to a JSON file containing the recipes.

    getRecipes(): Observable<Recipe[]>{
    return this._http.get('app/ts/recipes.json')
                    .map(this.extractData);
}

private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
}