问题描述
我有一个表单组件是父组件,而一个显示结果组件是子组件。 我对api进行了调用,并且必须使用回调来检索数据。 在服务层中,我打电话:
postSearchDocument(response: any,callback): void {
console.log('Response form in service layer: ',response);
const xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST',this.appConfig.getConfig().apiUrl + '' + this.appConfig.getConfig().searchDocument,true);
// build SOAP request
const soapRequest =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" ' +
'xmlns:bran="http://www.bottomline.com/soap/branch/">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<bran:CallBranch soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<JSONRequest xsi:type="xsd:string">' +
JSON.stringify(response) +
'</JSONRequest>' +
'</bran:CallBranch>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
console.log('SOAP REQUEST ');
console.log(soapRequest.toString());
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
this.returnValue = xmlhttp.responseText;
// alert(xmlhttp.responseText);
console.log('Response : ');
console.log(xmlhttp.responseText);
this.documentResponse = JSON.parse(this.returnValue)
);
console.log(this.documentResponse);
callback.apply(this,[this.documentResponse]);
// return this.documentResponse;
}
}
};
很明显,我将数据从父母传递给了孩子:
<app-show-results [documentsResponse]="documentsResponse"></app-show-results>
在父组件中,我有一个onSubmit方法,该方法允许我调用API:
this.apiService.postSearchDocument(this.searchRequest,this.getResponse);
这是我的回叫:
getResponse(response): void {
this.documentsResponse = response;
console.log('In callback response ',this.documentsResponse);
}
此API调用使用的是SOAP,我添加了一个回调以从服务器获取响应:
在我的子组件中,我确实有这个变量:
@input() documentsResponse;
我的问题是我没有在子组件中显示父项的返回值。我在子组件中添加了一个生命周期挂钩来监视更改:
ngOnChanges(changes: SimpleChanges): Promise<any> {
if (changes.documentsResponse && this.documentsResponse !== null) {
console.log(this.documentsResponse);
}
}
解决方法
在使用ChangeDetectionStrategy.OnPush
时,更改检测将受到限制,并且仅适用于某些情况。您需要标记父组件和子组件以在下一个周期中检查。尝试下面的代码
父组件
import { ...,ChangeDetectorRef } from '@angular/core'
@Component({})
class ParentComponent {
documentResponse: any
...
constructor(
private changeDetectorRef: ChangeDetectorRef
) {}
...
getResponse(response) {
this.documentResponse = response;
this.changeDetectorRef.markForCheck(); // Here is the fix
}
}