TypeScript - Angular 2 Dienst unter Verwendung von Fetch und Promise
Ich benutze Angular 2 Beta.
Ich versuche, einen HTTP-Dienst mit fetch zu erstellen, der Promises implementiert. Hier ist, was ich bisher habe:
HttpService.ts:
@Injectable()
export class HTTPService {
save(url: string, jsonPayload: JsonPayload): any {
window.fetch(url, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: jsonPayload
})
.then(status)
.then(json)
.then((response: any) => {
this.response = response;
return Promise.resolve(this.response);
})
.catch((error) => {
console.log(error.message);
return error.message;
});
}
}
Hier ist die dienstverbrauchende Klasse:
export class ConsumingComponent {
constructor(private _httpService: HTTPService) {
...
}
getSampleStuff() {
this._httpService
.save("http:sample.com/sample/stuff", this.jsonPayload)
.then(response => this.response = response);
this.sampleStuffModel = this.response;
}
}
Meine Absicht ist es, einen Webdienst asynchron aufzurufen.
So verstehe ich die Technologie:
- Initialisiere ein Promise im Dienst
- Injizieren Sie den Dienst in die konsumierende Klasse
- Fügen Sie in der konsumierenden Klasse ein ".then(...)" hinzu. Die Callback-Ergebnisse landen hier.
Ich habe versucht, ein Klassenmitglied ("this.response") auf die Antwort ("response") zu setzen.
Wenn ich dieses Versprechen ausführe, ist die Antwort null oder undefiniert.
Ich vermute, dass die Implementierung der resolve-Funktion die Ursache des Problems ist. Umgebe ich das gesamte window.fetch() mit einem resolve()?
Antwort #1
Zurückgegebene Werte steigen bei der Verwendung von Promises nicht durch die gesamte Kette auf.
window.fetch(...)
.then(status) // only status function will have the response
.then(json)
Vielleicht liege ich falsch, aber status und json scheinen keine Funktionen zu sein. Was versuchst du hier zu machen?
Ihr Servicecode funktioniert nicht wie erwartet zurück (ich habe auch status und json entfernt):
@Injectable()
export class HTTPService {
save(url: string, jsonPayload: JsonPayload): any {
// if you don't return anything, how the consumer will know it's a promise?
return window.fetch(url, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: jsonPayload
})
// do you really need to store the response into the service?
// .then((response: any) => {
// this.response = response;
// return Promise.resolve(this.response);
// })
.catch((error) => {
console.log(error.message);
// if you return error.message here, the consumer won't know there is a problem
// you need to rethrow the error so it can be catched by the consumer
throw error;
});
}
}
windows.fetch() ist bereits ein Promise, verpacke es nicht in ein resolve().
