user3887459
user3887459

Reputation: 15

Getting an error with "this" after converting to Typescript

My code looked like this but now I put it into a Typescript class and it gives me an error saying that "can't read property role of undefined".

    this.$http({
        method: 'POST',
        url: '/Token',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: 'grant_type=password&username=' + encodeURIComponent(userName) + '&password=' + encodeURIComponent(password),
    })
        .success(function (data, status, headers, cfg) {
            data.roles.split(':').forEach(function (v) {
                this.data.role['is' + v] = true;
                v == 'Test'
        })

Do I have to code my function differently with Typescript ? I have two function in the success(), can I replace this with => ?

Upvotes: 1

Views: 346

Answers (1)

David Bohunek
David Bohunek

Reputation: 3201

This in this case this means instance of the class where this code runs. You can definitely convert the functions to arrow functions (=>) and omit this. The code would look like this then:

this.$http({
    method: 'POST',
    url: '/Token',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: 'grant_type=password&username=' + encodeURIComponent(userName) + '&password=' + encodeURIComponent(password),
})
.success((data, status, headers, cfg) => {
    data.roles
        .split(':')
        .forEach((v) => {
            data.role['is' + v] = true;
            v == 'Test'
        })
});

Upvotes: 1

Related Questions