typescript - Fetch ve Promise Kullanan Angular 2 Servisi


Angular 2 beta sürümünü çalıştırıyorum.

Sözleşmeleri (promises) uygulayan bir fetch kullanarak bir http servisi oluşturmaya çalışıyorum. Şu ana kadar elimde olanlar şunlar:

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

İşte servisi kullanan sınıf:

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

Amacım bir web servis çağrısını eşzamansız olarak yapmak.
Teknolojiyi anlama şeklim şöyle:

  • Serviste bir Promise başlat
  • Hizmeti tüketici sınıfa enjekte edin
  • Tüketici sınıfta bir ".then(...)" ekleyin. Geri çağırma sonuçları buraya ulaşır.

Bir sınıf üyesini ("this.response") yanıtla ("response") eşleştirmeyi denedim.

Bu promise'i çalıştırdığımda, yanıt null veya tanımsız.

Tahmin ediyorum ki sorunun kaynağı resolve fonksiyonunun uygulanması. Tüm window.fetch() işlemini resolve() ile mi sarmalamalıyım?

Cevap #1

Promise kullanırken döndürülen değerler tüm zincir boyunca yayılmaz.

window.fetch(...)
  .then(status) // only status function will have the response
  .then(json)

Belki yanılıyorum ama status ve json fonksiyon gibi görünmüyor. Burada ne yapmaya çalışıyorsun?

Servis kodunuz beklediğiniz gibi bir dönüş sağlamıyor (ayrıca status ve json öğelerini de kaldırdım):

@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() zaten bir promise, bunu resolve() ile sarmayın.