typescript - angular'da toPromise()'dan nasıl değer alınır?
Angular uygulaması yapıyorum ve bu uygulamada şu şekilde bir servis çağrısı yapıyorum,
let newValue = this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise();
ve console.log(newValue) verir,
{"__zone_symbol__state":null,"__zone_symbol__value":[]}
Burada servisten gelen değeri newValue değişkenine saklamam gerekiyor.
Eğer toPromise.then.toPromise().then(function (result) { }) kullanırsam da aynı sonucu alıyorum.
Lütfen servisin değerlerini toPromise() ile newValue değişkenine kaydetmeme yardımcı olun.
Düzenle:
Yapıcı:
constructor(private http: HttpClient, private dynamicService: NgiDynamicFormsService) {
this.newArray = AppConfig.settings.template.templateFormJSON;
}
Async getQuestions()
async getQuestions() {
let questions: any = [];
this.newArray.forEach(element => {
if (element.elementType === 'textbox') {
questions.push(new TextboxQuestion(element));
} else if (element.elementType === 'dropdown') {
let newValue = await this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise();
element.options = newValue;
questions.push(new DropdownQuestion(element));
} else if (element.elementType === 'textarea') {
questions.push(new TextareaQuestion(element));
} else if (element.elementType === 'checkbox') {
questions.push(new CheckboxQuestion(element));
}
});
return questions.sort((a, b) => a.order - b.order);
}
Burada, newValue'i aldıktan sonra newValue'deki değerleri element.options'a göndermem gerektiğini görebilirsiniz.. Ve daha sonra bunun için questions.push(new DropdownQuestion(element)); çağırmam gerekiyor, newValue'deki değeri alamıyorum ve bu yüzden questions.push(new DropdownQuestion(element)) boş değerler veriyor, bu yüzden newValue'de değeri sakladıktan sonra, bunu çağırmam gerekiyor, questions.push(new DropdownQuestion(element))
Bu çağrıyı forEach fonksiyonu içinde yapmam gerekiyor, bu yüzden await kullanırsam, IDE şu hatayı veriyor,
[ts] 'await' expression is only allowed within an async function...
Cevap #1
Promise değerini okumak için zincirlenebilir .then operatörünü kullanın.
let newValue = this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise();
newValue.then((value)=>console.log(value));
Ayrıca async/await kullanabilirsiniz
async func(){
let newValue = await this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise();
}
----Promise.all----
async getQuestions() {
let questions: any = [];
let questionsPromise: any = [];
let questionsPromiseResult: any = [];
this.newArray.forEach(element => {
if (element.elementType === 'textbox') {
questions.push(new TextboxQuestion(element));
} else if (element.elementType === 'dropdown') {
questionsPromise.push( this.dynamicService.getRest(element.optionsUrl,localStorage.getItem('token')).toPromise());
questionsPromiseResult.push(element);
} else if (element.elementType === 'textarea') {
questions.push(new TextareaQuestion(element));
} else if (element.elementType === 'checkbox') {
questions.push(new CheckboxQuestion(element));
}
});
Promise.all(questionsPromise).then(results =>{
results.forEach(item,index=>{
let element = this.questionsPromiseResult[index];
element.options = item;
questions.push(new DropdownQuestion(element));
});
});
Cevap #2
Bir örnek veriyorum, umarım ne istediğinizi anlamanıza yardımcı olur:
servis dosyanızda:
getTransactions(): Promise<{any}> {
return this.http.get(`${Api.Url}transaction`).toPromise()
.then(r => {
return r;
}).catch(error => {
return Promise.reject(error);
});
}
ve o servisi kullanmak ve veri almak istediğiniz component.ts dosyanızda:
this.transactionService.getTransactions().then(
r => {
console.log(r);
}
).catch( e => {
alert('error fetching data');
});
