1

I am facing below issue when using the Angular 5 Services, Can you please help me what is wrong with the below code

I have gone through below questions but didn't help me

  1. Question 1
  2. Question 2
  3. Question 3

I just want to initialize the value in the class and use it in the method

Though I have defined the url value in the class I'm getting error as Cannot read property 'url' of undefined for the line console.log(this.url);

@Injectable()
export class OwnService {

    public accessTokenvalue = '';
    public url = 'https://www.someurl.com/id=';
    constructor(private hp: HelpService) {
    }

    public gethpPhotos() {
        this.hp.login()
            .then(function (response: LoginResponse) {
                console.log(response);
                console.log(this.url);

            })
            .catch((error: any) => console.error(error));
    }
}
1
  • I had the same issue then I just stop the angular cli listener then start again it solved Commented Dec 2, 2019 at 11:21

3 Answers 3

5

You just need to replace function (response: Response) with arrow function. Each function creates it's scope to which refers this inside it. Arrow function will preserve this.

.then((response: LoginResponse) => {
     console.log(response);
     console.log(this.url);
})
Sign up to request clarification or add additional context in comments.

Comments

2

You can resolve by using the context in which the 'url' exists:

public gethpPhotos() {
       var that = this; // outer context

        this.hp.login()
            .then(function (response: LoginResponse) {
                console.log(response);
                console.log(that.url); // <<<< changed to that.url for the outer context

            })
            .catch((error: any) => console.error(error));
    }

Comments

2

In your code this refers to the context of the http request. inorder to access the component variable, Use arrow function

this.hp.login()
.then(response: LoginResponse) => {
        this.answerList = response;
         console.log(this.url);
)

Comments

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.