How to use Fetch API in App Service #351
-
I want to use Fetch API in App Service and I tried to call
import { log } from "@zos/utils";
const logger = log.getLogger("some.appservice.logger");
AppService({
onInit(e) {
logger.log("on");
this.fetchRequest();
},
fetchRequest() {
this.request({
method: "FETCH_REQUEST",
})
.then((data) => { logger.log("sent"); })
.catch((res) => {});
},
});
import { BaseSideService } from "@zeppos/zml/base-side";
async function internalFetchRequest(res) {
try {
const response = await fetch({
url: "http://example.com",
method: "GET"
});
res(null, {
result: response.body,
});
} catch (error) {
res(null, {
result: "ERROR",
});
}
};
AppSideService(
BaseSideService({
onInit() {},
onRequest(req, res) {
console.log("=====>,", req.method);
switch (req.method) {
case "FETCH_REQUEST":
internalFetchRequest(res);
}
},
onRun() {},
onDestroy() {},
})
); |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 6 replies
-
App service also must be created/wrapped by zml library |
Beta Was this translation helpful? Give feedback.
-
You have to modify your code a bit to look like this @tererun: import { BasePage } from "@zeppos/zml/base-page";
AppService(
BasePage({
...,
fetchRequest() {
this.httpRequest({
method: 'POST',
url: "...",
body: {...},
})
.then((result) => {
...
}
}
} |
Beta Was this translation helpful? Give feedback.
-
Hey @silver-zepp - thanks for the help in trying to get this to work. I've been trying and I think I am just not understanding the layout of the framework. I think that the "app-service" and the "pages" code runs on the watch and the "app-side" runs on the phone in the Zepp app right? So I have an app where the page on the watch talks to the app-side code like this
And on the app side it looks like this
Where fetchDataFromTheInternet() uses a fetch to get data from a domain
All is good in the simulator and on the device and it works perfectly Following your instructions I created and added a app-service like so
and added to the JSON
Now the app still works fine in the simulator and does exactly what I want however it does not work on my real device - a BIP 5 Unity. I cannot get any data back from the AppSideService. Even if I dont do anything with the app-service as long as it is configured in the JSON I cannot get to the AppSideService. Is it possible to have an app-side and an app-service configured in the same app? Any help would be great, or even just an example that has pages, app-side and ap-service all working together, Thanks |
Beta Was this translation helpful? Give feedback.
You have to modify your code a bit to look like this @tererun: