实现需求:
1.build之前http获取json数据
2.创建一个Text文本,默认文本内容为:'还没有数据'
3.http加载成功后 文本内容修改为“http请求的json数据”
实现代码:
步骤一:引入http
import http from '@ohos.net.http';
步骤二:build之前http获取json数据
aboutToAppear(){ let httpRequest = http.createHttp(); httpRequest.on('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 "https:需要请求的url", { method: http.RequestMethod.GET, // 可选,默认为http.RequestMethod.GET // 开发者根据自身业务需要添加header字段 header: { 'Content-Type': 'application/json' }, }, (err, data) => { if (!err) { } else { console.info('error:' + JSON.stringify(err)); // 取消订阅HTTP响应头事件 httpRequest.off('headersReceive'); // 当该请求使用完毕时,调用destroy方法主动销毁。 httpRequest.destroy(); } } ); }
步骤三:创建Text文本
@State message: string = '还没有数据'
build() { Row({ space: 200 }) { Text(this.message) .height('300') .fontSize(14) .position({x:20,y:100}) .align(Alignment.Center) } }
步骤四:http加载成功后 文本内容刷新修改为“http请求的json数据”
全部代码实现:
import http from '@ohos.net.http'; @Entry @Component struct MyText { // 声明写在build之前 @State message: string = '还没有数据' aboutToAppear(){ let httpRequest = http.createHttp(); httpRequest.on('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 "https:需要请求的url", { method: http.RequestMethod.GET, // 可选,默认为http.RequestMethod.GET // 开发者根据自身业务需要添加header字段 header: { 'Content-Type': 'application/json' }, }, (err, data) => { if (!err) { this.message = JSON.stringify(data.result) } else { console.info('error:' + JSON.stringify(err)); // 取消订阅HTTP响应头事件 httpRequest.off('headersReceive'); // 当该请求使用完毕时,调用destroy方法主动销毁。 httpRequest.destroy(); } } ); } build() { Row({ space: 200 }) { Text(this.message) .height('300') .fontSize(14) .position({x:20,y:100}) .align(Alignment.Center) } } }
实现结果: