Http Request, this always returning undefined


#1

I am making a POST HTTP request to a server and it is working fine, i receive the information i desire and i can manipulate it however i want.

After that i try to write the information into XML and i can’t

As soon as i write -> “this.page.getViewById(“valueLastBill”);” It says this is undefined.
I tried outside of the method aswell but skips the requests and goes directly to getting the viewById of the page and sets with my predefined value instead of the value i get from the request

My code:

import { Page } from "ui/page";
import { Component, OnInit } from "@angular/core";
import { registerElement } from 'nativescript-angular';
import { BottomBar, BottomBarItem, TITLE_STATE, SelectedIndexChangedEventData, Notification } from 'nativescript-bottombar';
import { User } from "../../shared/model/user/user";
import { UserService } from "../../shared/model/user/user.service";
import { MovementService } from "../../shared/model/movement/movement.service";
import { Router, NavigationExtras } from "@angular/router";
import * as colorModule from "tns-core-modules/color";
import { ActivatedRoute } from "@angular/router";
import * as platformModule from "tns-core-modules/platform";
import { Config } from "../../shared/config";
import { Budget } from "../../shared/model/budget/budget";
import listView = require("ui/list-view");
var view = require("ui/core/view");
var applicationSettings = require("application-settings");

registerElement('BottomBar', () => BottomBar);

@Component({
    selector: "homePage",
    providers: [UserService, MovementService],
    templateUrl: "pages/homePage/homePage.html",
    styleUrls: ["pages/homePage/homePage-common.css", "pages/homePage/homePage.css"]
})
export class HomePageComponent implements OnInit {
    public hidden: boolean;
    public titleState: TITLE_STATE;
    public _bar: BottomBar;
    public inactiveColor: string;
    public accentColor: string;
    public user: User;
    public budget: Budget;
    public nameFromAPI: string;


    constructor(private router: Router, private page: Page, private route: ActivatedRoute, private userService: UserService, private movementService: MovementService) {
        this.route.queryParams.subscribe(params => {
            this.user = JSON.parse(params["user"]);
        })
        console.log("Inside HomePage");
        console.log("UserToken: " + Config.token);
        this.user.name = this.nameFromAPI;
    }


    public items: Array<BottomBarItem> = [
        new BottomBarItem(0, "Home", "ic_home_black_24dp", "white"),
        new BottomBarItem(1, "Menu", "ic_local_dining_black_24dp", "white"),
        new BottomBarItem(2, "Check-out", "ic_add_a_photo_black_24dp", "white"),
        new BottomBarItem(3, "Transactions", "ic_assignment_black_24dp", "white"),
        new BottomBarItem(4, "Settings", "ic_settings_black_24dp", "white")
    ];

    tabLoaded(event) {
        this._bar = <BottomBar>event.object;
        this.hidden = false;
        this.titleState = TITLE_STATE.ALWAYS_SHOW;
        var Color = colorModule.Color;
        var color = new Color("#8e8e93");
        this.inactiveColor = color.hex;
        this.accentColor = "black";
    }

    ngOnInit() {
        let navigationExtras: NavigationExtras = {
            queryParams: {
                "user": JSON.stringify({
                    "name": this.user.name,
                    "nif": this.user.nif,
                    "password": this.user.password
                })
            }
        };
        this.page.actionBarHidden = true;
        this.page.backgroundImage = "res://bitmap";

        var typeTransaction;
        var valueTransaction;
        var http = require("http");
        http.request({
            url: "http://192.168.1.73:8082/lastMovement",
            method: "POST",
            headers: { "Content-Type": "application/json" },
            content: JSON.stringify({ token: applicationSettings.getString("user.token", "default") })
        }).then(function (response) {
            var str = response.content.toString();
            var fields = str.split('"');
            //fields[0] is empty
            var valueLabel = fields[1];

            var value = fields[2];
            var noDoublePointValue = value.substring(1);
            var noCommaValue = noDoublePointValue.substring(0, noDoublePointValue.length - 1);

            var typeLabel = fields[3];
            //fields[4] is :
            var type = fields[5];
            var noInitialSpaceType = type.substring(1);

            typeTransaction = noInitialSpaceType;
            valueTransaction = noCommaValue;

            console.log("Type: " + typeTransaction);
            console.log("Value: " + valueTransaction);

            var htmlValueLastBill;
            htmlValueLastBill = this.page.getViewById("valueLastBill"); //<-- Error , this is undefined 
            if (typeof htmlValueLastBill == "undefined") {
                alert("Value undefined!");
            } else {
                htmlValueLastBill.text = "- € " + valueTransaction;
            }
        }, function (e) {
            console.log("error : " + e);
        });
        
            var htmlValueLastBill;
            htmlValueLastBill = this.page.getViewById("valueLastBill");
            if (typeof htmlValueLastBill == "undefined") {
                alert("Value undefined!");
            } else {
                htmlValueLastBill.text = "- € " + valueTransaction;
            }

            var htmlTypeLastBill;
            htmlTypeLastBill = this.page.getViewById("typeLastBill");
            if (typeof htmlTypeLastBill == "undefined") {
                alert("Type undefined!");
            } else {
                htmlTypeLastBill.text = typeTransaction;
            }
    }

Anyone has any idea why inside the HTTP POST Request i can’t call this?

Any hints on how to overcome this?


#2

I kinda found out the problem, it is because i am calling the POST Request this way:

http.request

instead of calling it like this

this.http.request

Therefore this is undefined inside the HTTP request.
But if i use this.http.request it is a completely different HTTP Request and much harder to work with.


#3

How come you dont use the angular http method? It’s really simple to work with and I can provide any examples you you need


#4

I managed to resolve the problem.

When you say angular HTTP method? you mean the ones that are in the documentation?

this ones: https://docs.nativescript.org/cookbook/http

Right?


#5

No, thats the nativescript http method. I mean this: https://angular.io/api/http/Http


#6

Thanks @mast3rd3mon, i’ll look into it, seems better than what i am using atm!


#7

It is nice and easy tbh. And anytime