HarmonyOS 如何在网络请求前添加Loading?

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
fox280

可以参考以下demo:

// CommonWindow.ets
import window from '@ohos.window';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
import { entryName } from './MainPage';

export class CommonWindow {
  private storage: LocalStorage | null = null;
  private subWindow: window.Window | null = null;
  private windowStage1: window.WindowStage | null = null
  private context: common.UIAbilityContext | null = null;

  private init() {
    this.context = getContext(this) as common.UIAbilityContext;
    let data: Data = { subWindowStage: null, storage: null };
    this.context.eventHub.emit("createWindow", data);
    this.windowStage1 = data.subWindowStage;
    this.storage = data.storage;
    console.log("aboutToAppear end createWindowStage");
    this.context.eventHub.on("closeWindow", (data: Data) => {
      this.destroySubWindow();
    })
  }

  showWindow() {
    this.init();
    if (this.subWindow) {
      console.log("subWindow is already exist");
      return;
    }
    try {
      if (!this.windowStage1) {
        console.error("this.windowStage1 is null");
        return;
      }
      this.windowStage1.createSubWindow('mySubWindow', (err: BusinessError, data) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
          return;
        }
        this.subWindow = (data as window.Window);
        console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data));
        if (!this.subWindow) {
          console.info('Failed to load the content. Cause: windowClass is null');
        } else {
          let names: Array<'status' | 'navigation'> = [];
          this.subWindow.setWindowSystemBarEnable(names);
          this.subWindow.setWindowTouchable(true);
          this.loadContent(entryName);
          this.showSubWindow();
        }
      });
    } catch (exception) {
      console.error('Failed to create the window. Cause: ' + JSON.stringify(exception));
    }
  }
  private showSubWindow() {
    if (this.subWindow) {
      this.subWindow.showWindow((err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error('Failed to show the window. Cause: ' + JSON.stringify(err));
          return;
        }
        console.info('Succeeded in showing the window.');
      });
    } else {
      console.info('showSubWindow subWindow not created.');
    }
  }

  private destroySubWindow() {
    if (this.subWindow) {
      this.subWindow.destroyWindow((err) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error('Failed to destroy the window. Cause:' + JSON.stringify(err));
          return;
        }
        this.subWindow = null
      });
    } else {
      console.info('showSubWindow subWindow not created.');
    }
  }

  private loadContent(path: string) {
    if (this.subWindow) {
      let that = this;
      let para: Record<string, number> = { 'PropA': 66 };
      that.storage = new LocalStorage(para);
      if (that.storage != null && this.subWindow != null) {
        that.storage.setOrCreate("windowObj", this.subWindow)
      }
      this.subWindow.loadContentByName(path, this.storage, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          return;
        }
        if (this.subWindow) {
          this.subWindow.setWindowBackgroundColor('#cc000e03')
        }
      });
    } else {
      console.info('loadContent subWindow not created.');
    }
  }
}

export interface Data {
  subWindowStage: window.WindowStage | null,
  storage: LocalStorage | null
}
//  MainPage.ets
import window from '@ohos.window';

export const entryName: string = 'loadingPage';

@Entry({ routeName: entryName, storage: LocalStorage.getShared() })
@Component
export struct MainPage {
  @LocalStorageLink('PropA') varA: number | undefined = 1;
  private subWindow: window.Window | undefined;

  build() {
    Column() {
      LoadingProgress().width(150)
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
    .width('100%')
  }

  // 页面生命周期:打开沉浸式
  onPageShow() {
    window.getLastWindow(getContext(this), (err, win) => {
      // 获取当前窗口的属性
      let prop: window.WindowProperties = win.getWindowProperties();
      // 打印当前窗口属性
      console.log(JSON.stringify(prop));
      win.setWindowLayoutFullScreen(true)
    })
  }

  // 页面生命周期:关闭沉浸式
  onPageHide() {
    window.getLastWindow(getContext(this), (err, win) => {
      win.setWindowLayoutFullScreen(false)
    })
  }

  aboutToAppear() {
    this.varA = LocalStorage.getShared().get<number>("PropA");
    this.subWindow = LocalStorage.getShared().get<window.Window>("windowObj");
  }
}

EntryAbility.ets中

1、增加subWindowStage定义

private subWindowStage: window.WindowStage | undefined = undefined;

2、onCreate增加监听

onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  const that: EntryAbility = this
  this.context.eventHub.on("createWindow", (data: Data) => {
  if (that.subWindowStage != undefined) {
  data.subWindowStage = that.subWindowStage
} else {
  hilog.info(0x0000, 'testTag', '%{public}s', 'that.subWindowStage == undefined');
}
})
}

3、onWindowStageCreate中增加赋值

this.subWindowStage = windowStage

使用

public httpRequest(reqMethod: http.RequestMethod, url: string): Promise<Object> {
  // 每一个httpRequest对应一个HTTP请求任务,不可复用
  let httpRequest = http.createHttp();
  let promise = httpRequest.request(url, {
    method: reqMethod,
    readTimeout: 10000,
    connectTimeout: 10000
  });

  new CommonWindow().showWindow();
  // Processes the data and returns.
  return new Promise((resolve, reject) => {
  promise.then((resp) => {
  this.closeSubWindow()
  if (resp.responseCode === http.ResponseCode.OK) {
  // Obtains the returned data.
  const respData:Object = typeof resp.result === 'string' ? JSON.parse(resp.result) : resp.result
  resolve(respData)
} else {
  httpRequest.destroy();
  reject('error')
}
}).catch((err:BusinessError) => {
  this.closeSubWindow()
  httpRequest.destroy();
  reject('error');
})
})
}

closeSubWindow() {
  let context = getContext(this) as common.UIAbilityContext;
  context.eventHub.emit("closeWindow", null);
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 网络请求loading
133浏览 • 1回复 待解决
HarmonyOS 网络请求loading
180浏览 • 1回复 待解决
HarmonyOS 如何在全局使用loading组件?
882浏览 • 1回复 待解决
鸿蒙JS开发 接口请求loading?
5792浏览 • 1回复 待解决
鸿蒙JS开发 接口请求loading??
6603浏览 • 1回复 已解决
鸿蒙JS开发 蓠接口请求loading?
3908浏览 • 1回复 待解决
HarmonyOS 网络请求header
140浏览 • 1回复 待解决
HarmonyOS 网络请求超时
143浏览 • 1回复 待解决
HarmonyOS 网络请求示例
174浏览 • 1回复 待解决