tsx
复制代码
网络
// 官网地址
https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Faxios#%E6%8B%A6%E6%88%AA%E5%99%A8
// 使用技巧
@ohos/axios(V2.2.8)
ohpm i @ohos/axios
// Request.ets
import { BusinessError } from '@kit.BasicServicesKit';
import axios, { AxiosResponse } from '@ohos/axios';
import { Logger } from 'commonlib';
/**
* todo: 1. 配置axios实例; 2. 在../apis目录下查看接口定义并对接真实后端
*/
const instance = axios.create({
baseURL: '',
timeout: 10 * 3000,
headers: {},
});
instance.interceptors.response.use(
(response: AxiosResponse) => {
if (response.status === 200) {
return Promise.resolve(response.data);
} else {
Logger.error(
'[Network]',
`https request failed:${response.config.url}. error:`,
JSON.stringify(response.status),
);
return Promise.reject(response);
}
},
(error: BusinessError) => {
Logger.error(
'[Network]',
`https request failed:. error:`,
JSON.stringify(error),
);
return Promise.reject(error);
},
);
export default instance;
// User.ets
import { UserLoginReq, UpdateUserInfoReq, MembershipInfoResp } from '../../types/responses/UserResponse';
import { BaseResponse } from '../../types/responses/BaseResponse';
import { RequestUrlMap } from '../../constants/Enums';
import request from '../Request'
class UserApis {
/**
* 用户登录
*/
public login(params?: UserLoginReq): Promise<BaseResponse> {
return request.get(RequestUrlMap.USER_LOGIN, { params })
}
/**
* 用户登出
*/
public logout(): Promise<BaseResponse> {
return request.get(RequestUrlMap.USER_LOGOUT)
}
/**
* 修改用户信息
*/
public updateUserInfo(data: UpdateUserInfoReq): Promise<BaseResponse> {
return request.put(RequestUrlMap.USER_INFO, data)
}
/**
* 开通/续费年卡会员
*/
public subscribeMembership(): Promise<BaseResponse> {
return request.post(RequestUrlMap.USER_MEMBERSHIP)
}
/**
* 查询会员信息
*/
public getMembershipInfo(): Promise<MembershipInfoResp> {
return request.get(RequestUrlMap.USER_MEMBERSHIP)
}
}
const instance = new UserApis();
export { instance as UserApis };
tsx
复制代码
### api的位置
https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-basic-components-navigation#%E7%A4%BA%E4%BE%8B1navigation%E9%A1%B5%E9%9D%A2%E5%B8%83%E5%B1%80
### pushPath
pathStack:NavPathStack = new NavPathStack()
// 需要在src/main目录下的module.json5配置文件中的module字段里配置"routerMap": "$profile:router_map",并在src/main/resources/base/profile目录下新增router_map.json。
this.controller.pushPath({
path: 'pages/DetailPage', // 目标页面的路径
params: { id: 101 }, // 传递的参数
onResult: (result) => { // 接收返回结果(可选)
console.info('收到返回结果:' + JSON.stringify(result));
}
});
### pushPathByName() 跳转
// 在点击事件中跳转
let p: UsrInfo = {name: "传递的参数", phone: "123456"}
this.pathStack.pushPathByName("DetailPage", p, (popInfo) => {
// 可选的回调函数,当从DetailPage返回时触发,popInfo.result包含返回的参数
console.log("收到返回参数: " + JSON.stringify(popInfo.result))
})
// 在DetailPage的build方法或事件中 接收
let params = this.pathStack.getParamByName("DetailPage") as UsrInfo[];
if (params && params.length > 0) {
let receivedData = params; // 获取第一个参数对象
console.log("收到参数: " + receivedData.name);
}
// 这种回调周期中也可以
.onReady((context: NavDestinationContext) => {
this.pathStack = context.pathStack;
// 直接通过上下文获取参数
this.usr = context.pathInfo.param as UsrInfo;
})
// 带有页面拦截机制
// Index.ets
@Entry
@Component
struct NavigationExample {
pageInfos: NavPathStack = new NavPathStack();
isUseInterception: boolean = false;
registerInterception() {
this.pageInfos.setInterception({
// 页面跳转前拦截,允许操作栈,在当前跳转中生效。
willShow: (from: NavDestinationContext | "navBar", to: NavDestinationContext | "navBar",
operation: NavigationOperation, animated: boolean) => {
if (!this.isUseInterception) {
return;
}
if (typeof to === "string") {
console.info("target page is navigation home");
return;
}
// 重定向目标页面,更改为pageTwo页面到pageOne页面。
let target: NavDestinationContext = to as NavDestinationContext;
if (target.pathInfo.name === 'pageTwo') {
target.pathStack.pop();
target.pathStack.pushPathByName('pageOne', null);
}
},
// 页面跳转后回调,在该回调中操作栈在下一次跳转中刷新。
didShow: (from: NavDestinationContext | "navBar", to: NavDestinationContext | "navBar",
operation: NavigationOperation, isAnimated: boolean) => {
if (!this.isUseInterception) {
return;
}
if (typeof from === "string") {
console.info("current transition is from navigation home");
} else {
console.info(`current transition is from ${(from as NavDestinationContext).pathInfo.name}`);
}
if (typeof to === "string") {
console.info("current transition to is navBar");
} else {
console.info(`current transition is to ${(to as NavDestinationContext).pathInfo.name}`);
}
},
// Navigation单双栏显示状态发生变更时触发该回调。
modeChange: (mode: NavigationMode) => {
if (!this.isUseInterception) {
return;
}
console.info(`current navigation mode is ${mode}`);
}
})
}
build() {
Navigation(this.pageInfos) {
Column() {
Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.pageInfos.pushPath({ name: 'pageOne' }); // 将name指定的NavDestination页面信息入栈
})
Button('use interception', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.isUseInterception = !this.isUseInterception;
if (this.isUseInterception) {
this.registerInterception();
} else {
this.pageInfos.setInterception(undefined);
}
})
}
}.title('NavIndex')
}
}
// 原始示例
import { Logger } from '../logger/Index';
import { NavRouterInfo, DialogInfo } from './Types';
const TAG: string = '[RouterModule]';
export class RouterModule {
private static _stack: NavPathStack = new NavPathStack();
public static getStack() {
return RouterModule._stack;
}
// 跳转到指定路由栈的指定路由页面
public static push(info: NavRouterInfo, animated?: boolean) {
try {
RouterModule._stack.pushPathByName(
info.url,
info.param,
info.onPop,
animated,
);
} catch (err) {
Logger.error(TAG, 'navigation stack push failed::' + JSON.stringify(err));
}
}
// 将指定路由栈的栈顶页面退出,将info指定的NavDestination页面信息入栈
public static replace(info: NavRouterInfo) {
try {
RouterModule._stack.replacePathByName(info.url, info.param);
} catch (err) {
Logger.error(
TAG,
'navigation stack replace failed::' + JSON.stringify(err),
);
}
}
// 弹出栈顶元素
public static pop(result?: Object, animated?: boolean) {
try {
RouterModule._stack.pop(result, animated);
} catch (err) {
Logger.error(TAG, 'navigation stack pop failed::' + JSON.stringify(err));
}
}
// 回退路由栈到由栈底开始第一个名为name的NavDestination页面
public static popToName(name: string, animated?: boolean) {
try {
RouterModule._stack.popToName(name, animated);
} catch (err) {
Logger.error(
TAG,
'navigation stack pop to name failed::' + JSON.stringify(err),
);
}
}
// 关闭全局弹窗
public static closeDialog<T>(result?: DialogInfo<T>) {
try {
RouterModule._stack.pop(result);
} catch (err) {
Logger.error(TAG, 'close dialog failed::' + JSON.stringify(err));
}
}
// 清除栈中的所有页面
public static clear(animated?: boolean) {
try {
RouterModule._stack.clear(animated);
} catch (err) {
Logger.error(
TAG,
'navigation stack clear failed::' + JSON.stringify(err),
);
}
}
// 获取指定栈中指定页面的参数,不支持栈内存在多个同名页面的情况
public static getNavParam<T = object>(info: NavRouterInfo): T | undefined {
try {
const paramsArr = RouterModule._stack.getParamByName(info.url) as T[] | undefined[];
if (paramsArr.length) {
const lastParam = paramsArr[paramsArr.length - 1];
if (typeof lastParam !== 'undefined') {
return lastParam;
}
}
} catch (err) {
Logger.error(
TAG,
'navigation stack get params failed::' + JSON.stringify(err),
);
}
return undefined;
}
// 获取栈大小
public static size() {
return RouterModule._stack.size();
}
}