HarmonyOS鸿蒙Next万能卡片-Codelabs挑战赛:云函数计算十二生肖卡片
HarmonyOS鸿蒙Next万能卡片-Codelabs挑战赛:云函数计算十二生肖卡片
应用介绍
云函数计算十二生肖卡片,是参考学习了狼哥一篇云函数计算十二生肖旧文章,在API9 3.1版本环境下改进和优化端侧云函数入口调用和UI界面,顺便做成卡片形式的简单应用。
- 元服务卡片,在桌面上添加2x2元服务卡片,能够显示当前年份和生肖。
- 根据选择的年份,云函数计算生肖后返回端侧显示生肖。
云函数端侧开发和测试
云函数云侧测试
主界面开发代码:
import { Logger } from '[@ohos](/user/ohos).hilog';
import { Request } from '../Api/Index';
import { Loading } from './loading';
@Entry
@Componentstruct ZodiacPage {
private zodiac: Array<string> = ["猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊"];
@State year: string = "2022"
private select: number = 1
private yearRange: string[] = ['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020','2021','2022','2023']
@State born: string = "?"
@State loading: boolean = false
build() {
Stack(){
Image($rawfile('background.JPG'))
.width('100%')
.height('100%')
.objectFit(ImageFit.Fill)
Column({space: 20}) {
Text('请选择年份')
.fontSize(20)
.fontWeight(FontWeight.Bold)
TextPicker({ range: this.yearRange, selected: this.select })
.onChange((value: string, index: number) => {
console.info('Picker item changed, value: ' + value + ', index: ' + index)
this.year = value
})
// 计算按钮操作
Button('计算', {type: ButtonType.Normal, stateEffect: true})
.fontSize(18)
.borderRadius(8)
.width(100)
.margin({bottom: 20})
.onClick(() => {
// 根据年份计算生肖
this.getBorn()
})
if (this.loading) {
Loading()
}else{
// 显示计算结果
Text(`${this.year} 年生肖是 ${this.born}`)
.fontSize(20)
.fontWeight(FontWeight.Bold)
}
}
.width('100%')
.height('100%')
.padding({top: '33%'})
}
}
//eTS端计算十二生肖
// getBorn() {
// let idx = this.year%12
// this.born = this.zodiac[idx]
// }
//eTS端调用云函数计算十二生肖
async getBorn() {
this.loading = true
let params = {
"year": this.year
}
var JsonObject = await Request.invoke('zodiacfunc-$latest', params)
this.born = JsonObject.zodiac
Logger.error(1,"error",JSON.stringify(this.born))
if(this.born != '?'){
this.loading = false
}
}
}
卡片界面开发代码:
@Entry
@Componentstruct WidgetCard {
readonly MAX_LINES: number = 1;
readonly ACTION_TYPE: string = 'router';
readonly MESSAGE: string = '请点击计算十二生肖';
readonly ABILITY_NAME: string = 'EntryAbility';
readonly FULL_WIDTH_PERCENT: string = '100%';
readonly FULL_HEIGHT_PERCENT: string = '100%';
private zodiac: Array<string> = ["猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊"];
@State year: string = "2022"
@State born: string = "?"
aboutToAppear() {
let date = new Date();
this.year = date.getFullYear().toString()
let idx = parseInt(this.year)%12
this.born = this.zodiac[idx]
}
build() {
Stack() {
Image($rawfile('background.JPG'))
.width(this.FULL_WIDTH_PERCENT)
.height(this.FULL_HEIGHT_PERCENT)
.objectFit(ImageFit.Fill)
Column({space: 20}) {
Text('请点击计算十二生肖')
.fontSize(12)
.fontWeight(FontWeight.Bold)
// 显示计算结果
Text(`${this.year} 年生肖是 `+ `${this.born}`)
.fontSize(15)
.fontWeight(FontWeight.Bold)
}
.width('100%')
.height('100%')
.padding({top: '33%'})
}
.width(this.FULL_WIDTH_PERCENT)
.height(this.FULL_HEIGHT_PERCENT)
.onClick(() => {
postCardAction(this, {
"action": this.ACTION_TYPE,
"abilityName": this.ABILITY_NAME,
"params": {
"message": this.MESSAGE
}
});
})
}
}
界面云函数入口代码:
Index.ets代码如下:
import { request } from './Request';
export const Request = new request(getContext(this));
Request.ets代码如下:
import { Function } from './Function';
// 云函数请求类
export class request {
private function: Function;
constructor(context) {
this.function = Function.instance(context);
}
async invoke(trigger?: string, params?: object) {
return await this.function.call(trigger, params);
}
}
Function.ets代码如下:
import { Logger } from '[@ohos](/user/ohos).hilog';
import agconnect from '[@hw-agconnect](/user/hw-agconnect)/api-ohos';
import "[@hw-agconnect](/user/hw-agconnect)/core-ohos";
import "[@hw-agconnect](/user/hw-agconnect)/credential-ohos";
import "[@hw-agconnect](/user/hw-agconnect)/function-ohos";
// 云函数工具类
export class Function {
static _instance: Function;
constructor(context) {
this.initAgc(context);
}
static instance(context) {
if (!Function._instance) {
Function._instance = new Function(context);
}
return Function._instance;
}
private async initAgc(context) {
try {
agconnect.instance().init(context);
let credentialService = agconnect.credential();
await credentialService!.removeToken();
Logger.info(0, "Function", "init AGC SDK success");
} catch (err) {
Logger.error(0, "Function", "initAgcSDK failed" + err);
}
}
// 调用云函数计算十二生肖
async call(trigger,params) {
try {
let functionCallable = agconnect.function().wrap(trigger);
let functionResult = await functionCallable.call(params);
return functionResult.getValue();
//return functionResult.getValue().result;;
} catch (err) {
Logger.error(0, "Function", 'catch a err: ' + err);
}
}
}
### 总结
通过开发和测试云函数,进行端云一体化开发元服务卡片,收获不少知识和经验,特别是云测和端侧测试云函数调用时是不一样的,暂时的坑可能需要华为官方以后更新,参考了狼哥的一篇云函数计算十二生肖旧文章(好像他本人删除,找不到引用文章), 总结这个项目用到以下知识点:
- 使用端云一体化开发元服务卡片
- 开发和测试云函数
更多关于HarmonyOS鸿蒙Next万能卡片-Codelabs挑战赛:云函数计算十二生肖卡片的实战教程也可以访问 https://www.itying.com/category-93-b0.html
3 回复
你的
import Loading from './loading';
loading相关的代码没有贴出来。
贴一下吧,正在学习中,谢谢了。
更多关于HarmonyOS鸿蒙Next万能卡片-Codelabs挑战赛:云函数计算十二生肖卡片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
loading代码很简单可有可无的,供参考如下:
@Entry
@Component
export default struct Loading {
@State rotated: boolean = false
build() {
Stack(){
Circle()
.width(30)
.height(30)
.fillOpacity(0)
.stroke("#121212")
.strokeWidth(5)
.padding(5)
Column(){
Circle()
.width(5)
.height(5)
.fill(117440527)
.stroke(117440527)
.strokeWidth(3)
}.height(35)
}
.rotate({
z:1,
angle: this.rotated ? 0 : -360,
centerX: '50%',
centerY: '50%'
})
.animation({
duration:1000,
curve: Curve.Linear,
iterations: -1
})
.onAppear(()=> {
this.rotated = !this.rotated
})
.height('100%').width('100%')
}
}