Ricerca nel sito web

Impossibile leggere la proprietà somevalue di undefined in Typescript Angular 5


Sto affrontando il seguente problema nell'utilizzo dei servizi Angular 5, puoi per favore aiutarmi a capire cosa non va nel codice qui sotto

Ho esaminato le domande seguenti ma non mi hanno aiutato

  1. Domanda 1
  2. Domanda 2
  3. Domanda 3

Voglio solo inizializzare il valore nella classe e usarlo nel metodo

Anche se ho definito il valore dell'URL nella classe, ricevo l'errore Cannot read property 'url' of undefined per la riga 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));
    }
}

Risposta n. 1

Devi solo sostituire function (response: Response) con una funzione freccia. Ogni function crea il proprio ambito a cui si riferisce this al suo interno. La funzione freccia manterrà this.

.then((response: LoginResponse) => {
     console.log(response);
     console.log(this.url);
})

Risposta n. 2

Puoi risolvere utilizzando il contesto in cui esiste l'URL:

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));
    }