HarmonyOS鸿蒙Next中AlertDialog.show在http.request内不显示

HarmonyOS鸿蒙Next中AlertDialog.show在http.request内不显示

interface User {
  name: string
}

interface DataSet {
  code: string
  data: User
}
let httpRequest = http.createHttp();
httpRequest.request(
  'https://api.xxxxxxxxx.com/test',
  {
    method: http.RequestMethod.GET,
    header: {
      'Content-Type': 'application/json'
    },
    expectDataType: http.HttpDataType.OBJECT
  },
  (err, data) => {
    if (!err) {
      let response = data.result as DataSet;
      console.log(response.data.name);
      AlertDialog.show({
        message: response.data.name,
        confirm: {
          value: '确认',
          action: () => {}
        }
      })
    }
  })

如上的代码,console.log在控制台有输出,但下边的AlertDialog.show(),未显示弹窗,包括使用Promise方式,也同样不显示弹窗。有朋友知道是什么原因吗?

DevEco Studio 5.0.3.906 API 12


更多关于HarmonyOS鸿蒙Next中AlertDialog.show在http.request内不显示的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

更多关于HarmonyOS鸿蒙Next中AlertDialog.show在http.request内不显示的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,AlertDialog.showhttp.request内不显示的问题,通常与UI线程和网络请求线程的执行顺序有关。http.request是异步操作,可能在网络请求完成时,UI线程已经结束,导致AlertDialog无法正确显示。解决此问题,可以将AlertDialog.show放置在http.request的回调函数中,确保在网络请求完成后,UI线程仍处于活动状态。例如:

http.request({
  url: 'https://example.com/api',
  method: 'GET',
  success: function (response) {
    AlertDialog.show({
      title: 'Response',
      message: 'Request successful',
      buttons: [
        {
          text: 'OK',
          color: '#0000FF'
        }
      ]
    });
  },
  fail: function (error) {
    AlertDialog.show({
      title: 'Error',
      message: 'Request failed',
      buttons: [
        {
          text: 'OK',
          color: '#FF0000'
        }
      ]
    });
  }
});

这样可以确保AlertDialog在网络请求完成后显示。

在HarmonyOS鸿蒙Next中,AlertDialog.showhttp.request内不显示,可能是由于网络请求是异步操作,导致UI更新未能及时响应。建议将AlertDialog.show放在http.request的回调函数中执行,确保在网络请求完成后再显示对话框。例如:

http.request({
  url: 'https://example.com/api',
  success: function(response) {
    AlertDialog.show({
      message: '请求成功',
      buttons: [{ text: '确定' }]
    });
  },
  fail: function(error) {
    AlertDialog.show({
      message: '请求失败',
      buttons: [{ text: '确定' }]
    });
  }
});

这样可以确保对话框在请求完成后再显示。

回到顶部