SymptomWhen I entered a value in the input box and submitted it, the mandatory item verification failed, and the system displayed a message indicating that a parameter was empty and instructed me to enter a value. The code for obtaining the input value is as follows:
e.target.attr.value, this.$element(‘#id’).attr.value
AnalysisThe possible cause is that the method for obtaining the value is incorrect. As a result, the value in the input box cannot be obtained.
SolutionI used the onchange event to assign a value to the model and obtained the value from the input box. The method is as follows:
1. Initialize the model.
JavaScript:
data:{
accountValue:''
}
2. Bind an event to the input box.
HTML:
<input @change="getAccountValue" value="{{accountValue}}"></input>
3. Assign a value.
JavaScript:
getAccountValue: function(e) {
this.accountValue = e.value // Here, e.value instead of e.target.attr.value is used.
}
Suggestions and SummaryRefer to the official document instead of generating a JavaScript object for coding. A JavaScript object may lead to compatibility issues.
Currently, the data binding mode of a quick app is unidirectional.
1. The value entered in the input box does not change the value of accountValue in data.
2. If the value in input box is changed by setting this.accountValue to xxx, the onchange event of the input will not be triggered.
3. In this.accountValue = xxx format, if the value of accountValue before and after the change remains the same, the page will not be re-rendered.
Related
Assigning App Permissions
The Android OS provides two location permissions: ACCESS_COARSE_LOCATION (approximate location permission) and ACCESS_FINE_LOCATION (precise location permission). These permissions are already defined in plugin.xml as follows:
Code:
<!--Fused Location-->
<config-file target="AndroidManifest.xml" parent="/*">
<!--...-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!--...-->
</config-file>
In Android Q, if your app needs to continuously locate the device location when it runs in the background, you need to apply for the ACCESS_BACKGROUND_LOCATION permission. This permission is already defined in plugin.xml as follows:
Code:
<!--Fused Location-->
<config-file target="AndroidManifest.xml" parent="/*">
<!--...-->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<!--...-->
</config-file>
Using the Location Service Class
The Java class defined for Fused Location service of Location Kit is HMSFusedLocation.
To use it on Cordova, you should initilize Fused Location service of Location Kit with HMSFusedLocation.init() method before using other methods of HMSFusedLocation.
Code:
// Initialize
LocationKitHMSLocationKit.init();
HMSFusedLocation.init();
Checking the Device Location Settings
Device location settings will affect the location result of HUAWEI Location Kit. For example, if the location function is disabled on a device, the device location cannot be obtained. Therefore, you are advised to check whether the device settings meet the location requirements before continuously obtaining location information. HUAWEI Location Kit provides the capability of checking device location settings.
If the location settings do not meet the location requirements, your app can prompt users to enable related permissions. (The location permission must be enabled for HMS Core (APK). In Android Q, Location must be set to Always for HMS Core.)
You can obtain the location settings using the checkLocationSettings(locationSettingsRequest) method.
The locationSettingsRequest object is an input parameter of the method and has three attributes: locationRequest, alwaysShow, and needBle.
The following is the sample code for creating a locationRequest object:
Code:
const locationRequest = () => { return {
id: 'locationRequest' + Math.random() * 10000,
priority: HMSFusedLocation.PriorityConstants.PRIORITY_HIGH_ACCURACY,
interval: 3,
numUpdates: 10,
fastestInterval: 1000.0,
expirationTime: 200000.0,
expirationTimeDuration: 200000.0,
smallestDisplacement: 0.0,
maxWaitTime: 2000000.0,
needAddress: true,
language: 'en',
countryCode: 'en',
}};
Then, following code can be used to create a locationSettingsRequest object:
Code:
const locationSettingsRequest = () => { return {
alwaysShow: true,
needBle: true,
locationRequests: [locationRequest()]
}};
The needBle attribute indicates whether BLE scanning needs to be enabled. The options are true (yes) and false (no).
The alwaysShow attribute indicates whether a location is required for the app to continue. The options are true (yes) and false (no).
Finally, call the checkLocationSettings() method to obtain the location settings. The method returns a response containing the result.
Code:
const locationSettingsResult = await HMSFusedLocation.checkLocationSettings(locationSettingsRequest());
Obtaining the Last Known Location
An app can use the HUAWEI Location Kit service API to obtain the last known location of a device. In most cases, the last known location is the current location of the device. The following is the sample code for calling the getLastLocation() method to obtain the last known location.
The method has no input parameter and returns a response containing the location data.
Code:
const lastLocation = await HMSFusedLocation.getLastLocation();
Continuously Obtaining the Location Information
To enable your app to continuously obtain the device location, you can use the requestLocationUpdates() and registerHMSEvent(eventName, handler) methods provided by HUAWEI Location Kit.
First, you need to create a locationRequest object as in the example of checking the device location settings. Then, you need to call the requestLocationUpdates() method.
This method is used to request location updates using the callback on the specified Looper thread, and then returns the location request ID, if the request was successful.
Code:
const requestLocationUpdatesResult = await HMSFusedLocation.requestLocationUpdates(locationRequest());
console.log({requestLocationUpdatesResult});
Then, call the method registerHMSEvent(eventName, handler) that handles the HMS update events.
Code:
registerHMSEvent(HMSFusedLocation.Events.SCANNING_RESULT, (result) => {
console.log('new location update');
})
Using the Mock Location
Note:
To use the mock location function, go to Settings > System & updates > Developer options > Select mock location app and select the app for using the mock location function.
(If Developer options is unavailable, go to Settings > About phone and tap Build number for seven consecutive times. Then, Developer options will be displayed on System & updates.)
Mock location feature can be enabled or disabled with the following method: setMockMode( boolean ).
This takes a boolean as argument, which indicates whether mock mode should be enabled or disabled.
The method returns a promise with the result, which should be resolved.
Code:
const setMockModeResult = await HMSFusedLocation.setMockMode(true);//or "false" to disable
Coordinates of the mock location can be set with the following method: setMockLocation({ latitude, longitude })
The method takes a single object as an argument, which contains the properties latitude and longitude.
Then the method returns the result with a promise, which should be resolved.
Code:
const setMockLocationResult = await HMSFusedLocation.setMockLocation({
latitude: parseFloat(latitude),
longitude: parseFloat(longitude)
});
console.log({setMockLocationResult});
Once the mock location function is enabled and set, your app will return the specified location data when trying to obtain the last location information.
If we briefly talk about what HMS Site Kit is, you can provide users to explore the world faster with Site Kit. You can search for locations by keywords, find places which are close to the specified coordinate point, get detailed information about a place and get suggestions for places by keyword.
We can get detailed information about a place with Place Detail Search, another feature of Site Kit. The only condition for this, we need to know Site model’s id value that belongs to the place we want to search.
Before I explain the use of Place Detail Search, I would like to share with you a function that we can use this feature.
Code:
fun placeDetail(siteId: String){
val searchService = SearchServiceFactory.create(context,
URLEncoder.encode(
"Your-API-KEY",
"utf-8"))
var request = DetailSearchRequest()
request.siteId = siteId
request.language = Locale.getDefault().language // Getting system language
searchService.detailSearch(request, object: SearchResultListener<DetailSearchResponse>{
override fun onSearchError(searchStatus: SearchStatus?) {
Log.e("SITE_KIT","${searchStatus?.errorCode} - ${searchStatus?.errorMessage}")
}
override fun onSearchResult(detailSearchResponse: DetailSearchResponse?) {
var site = detailSearchResponse?.site
site?.let {
Log.i("SITE_KIT", "Name => ${it.name}," +
"Format address => ${it.formatAddress}, " +
"Coordinate => ${it.location.lat} - ${it.location.lng}, " +
"Phone => ${it.poi.phone}, " +
"Photo URLS => ${it.poi.photoUrls}, " +
"Rating => ${it.poi.rating}, " +
"Address Detail => ${it.address.thoroughfare}, ${it.address.subLocality}, " +
"${it.address.locality}, ${it.address.adminArea}, ${it.address.country}")
} ?: kotlin.run {
Log.e("SITE_KIT","Site Place couldn't find with the given site ID")
}
}
})
}
First, we need to create a SearchService object from the SearchServiceFactory class. For this, we can use the create() method of the SearchServiceFactory class. We need to declare two parameters in create() method.
The first of these parameters is context value. It is recommended that Context value should be in Activity type. Otherwise, when HMS Core(APK) needs to be updated, we can not receive any notification about it.
The second parameter is API Key value that we can access via AppGallery Connect. This value is generated automatically by AppGallery Connect when a new app is created. We need to encode API parameter as encodeURI.
After creating our SearchService object as I described above, we can create a DetailSearchRequest object. We will specify the necessary parameters on this object related to the place which we want want to get information.
After creating our DetailSearchRequest object, we can determine parameters for a place that we want to get information. Two parameters are specified here:
SiteId: There is a unique id value for each Site in Site Kit. This parameter is used to specify the id value of the place whose information is to be obtained.
Language: It is used to specify the language that search results have to be returned. If this parameter is not specified, language of the query field we have specified in the query field is accepted by default. In example code snippet in above, language of device has been added automatically in order to get a healthy result.
After entering the id value and language parameter of the place that we want to learn in detail, we can start learning the details. For this, we will use detailSearch() method of the SearchService object. This method takes two parameters.
For the first parameter, we must specify DetailSearchRequest object we have defined above.
For the second parameter, we have to implement SearchResultListener interface. Since this interface has a generic structure, we need to specify class belonging to the values to be returned. We can get the incoming values by specifying DetailSearchResponse object. Two methods should be override with this interface. onSearchError() method is executed if operation fails, and onSearchResult() method is executed if operations is successful. There is one value in DetailSearchResponse. This value is Site object that belongs to the id value. With the Site variable of DetailSearchResponse object, we can access information belong to place we have searched.
sujith.e said:
Hi,Why API key is required?
Click to expand...
Click to collapse
API key is a simple credential for accessing Huawei services. Your API key is creating automatically on the AppGallery Connect when you create an application, and then your app can use the key to call public APIs provided by Huawei.
When an app calls a public API provided by Huawei, we should give this information to API to help Huawei to identify our application.
Your HUAWEI ID is the account that can be used to access all Huawei services, for example, the HUAWEI Consumer Cloud service, GameCenter, and AppGallery.
The use of HUAWEI IDs is based on the OAuth2.0 protocol. After obtaining authorization from users, apps can obtain users' basic information from the HUAWEI ID system, including OpenID, access tokens, nicknames, and avatars.
OpenID: After a user signs in using a HUAWEI ID, an app can obtain a unique ID opened by the HUAWEI ID. This unique ID is the OpenID. For the same HUAWEI ID, an OpenID is unique for each app and will always be the same for the same app, that is, the OpenID varies according to the app.
Difference between UnionID and OpenID: When the same HUAWEI ID is used to sign in to different apps, the returned OpenID values are different, but the UnionID values are the same. Therefore, if you need to uniquely identify a user among multiple apps, UnionID can be used.
You can obtain the OpenID after accessing HUAWEI Account Kit. However, to obtain the UnionID, you need to select Enable for Enable UnionID when applying for a HUAWEI ID.
Currently, the following two access token grant types are available for your now: implicit and authorization code.
● Implicit:
A quick app can directly call the authorize API to obtain an access token, which has a default validity period of 3600 seconds. When the access token expires, the quick app needs to call the API to obtain authorization again.
● Authorization code:
The authorization process adopting this grant type is also referred to as the web server flow. It applies to all apps with a server.
The web server flow consists of two steps:
1. A quick app calls the authorize API to obtain an authorization code.
2. The quick app calls the API provided by Huawei server to exchange the authorization code for information including an access token and a refresh token.
Preparations
1. Ensure that you have applied for HUAWEI Account Kit on HUAWEI Developer.
For details, please refer to Applying for HUAWEI Account Kit.
2. Install the development tool by referring to Installing the Development Tool.
HUAWEI Account Kit is extended by HUAWEI and does not comply with vendors' standards. You need to access the kit through Huawei quick app IDE.
Accessing HUAWEI Account Kit
Implicit Grant Type
You must be a company developer whose identity has been verified by HUAWEI Developer.
The app ID for which you need to apply for the permission must be created by the developer account that you have provided.
The app for which you need to apply for the permission is not a finance app.
Application method: Download the Quick App - HUAWEI ID-associated Mobile Number and Email Address Access Permission Application Form (App Name & App ID).xlsx, fill in the form, and send it to [email protected]. Then your application will be reviewed and handled.
1. Call the account.getProvider API in your quick app to check whether the current device supports HUAWEI Account Kit.
Only the return value huawei indicates that the device supports HUAWEI Account Kit. To support HUAWEI Account Kit is the premise on which the following function development and API calls can continue.
2. Call the account.authorize API in the quick app to obtain an access token.
3. Call the account.getProfile API to obtain basic user information, including the OpenID, nickname, and avatar of the user.
Import the following API to the quick app and call the getProfile method.
4. Call account.getPhoneNumber API to obtain the user's mobile number. Before using this function, you need to apply to Huawei for related permissions.Before calling getPhoneNumber, call authorize to obtain the access token again by passing the value scope.mobileNumber for the scope parameter.Import the following API to the quick app and call the getPhoneNumber method.
Authorization Code Grant Type
1. Call the account.getProvider API in your quick app to check whether the current device supports HUAWEI Account Kit.
Only the return value huawei indicates that the device supports HUAWEI Account Kit. To support HUAWEI Account Kit is the premise on which the following function development and API calls can continue.
2. Check whether the authorization code needs to be obtained again.
● If the authorization code has not been obtained or the authorization code has expired according to the response of the account.checkUserSession API, go to Step 3.
● If the current session is still valid according to the response of the account.checkUserSession API, go to Step 5.
3. Call the account.authorize API in the quick app to obtain an authorization code.
import account from '@service.account'
account.authorize(OBJECT)
OBJECT Parameter
ParameterTypeMandatory or OptionalDescriptionappidStringMandatoryUnique ID allocated to a quick app created on HUAWEI Developer. For details, please refer to section "Obtaining the APP ID" in Creating a Quick App.typeStringMandatoryThe parameter has a fixed value of code for the authorization code type.redirectUriUriOptionalLeave this parameter empty.scopeStringYesScope of the permissions that are applied. Currently, only cope.baseProfile is supported.
A success response to the calling of the authorize API in the authorization code grant type contains the following parameters.
ParameterTypeDescriptioncodeStringAuthorization code returned when the authorization code grant type is adopted.
Caution:
An authorization code is valid only for five minutes and can be used only once.
4. Call the API for exchanging the authorization code for an access token from the server.
To obtain an access token, send a request using the POST method from the app's server to the Huawei OAuth 2.0 authorization service address https://oauth-login.cloud.huawei.com/oauth2/v2/token with the following mandatory parameters contained in the request body:
Caution:
Input parameters must be urlencoded.
● grant_type: This parameter has a fixed value of authorization_code.
● code: authorization code obtained in the previous step.
● client_id: app ID obtained when you create an app on HUAWEI Developer.
● client_secret: app secret obtained when you create an app on HUAWEI Developer. This parameter is mandatory.
● redirect_uri: This parameter has a fixed value of hms://redirect_url.
POST /oauth2/v2/token HTTP/1.1
Host: login.cloud.huawei.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=Etersdfasgh74ddga%3d&client_id=12345&client_secret=0rDdfgyhytRtznPQSzr5pVw2&redirect_uri=hms%3A%2F%2Fredirect_url
If there are no errors in the request, the authentication server will send a JSON string consisting of the following parameters:
● access_token: access token to be obtained. If an access_token contains backslashes (\), remove all of them.
● expires_in: validity period of the access token, in seconds.
● refresh_token: token used to obtain a new access token. This parameter is returned for all apps.
● scope: access scope of the access token, that is, the list of permissions granted by the user.
Sample code:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{
"access_token": "346346sdxcdfsa3566546dfdfgfg=",
"expires_in": 3600,
"refresh_token": "68dieddfg08349786gdgfsdfa=",
"scope": "base"
}
If there are errors in the request, the authentication server will send a JSON string consisting of the following parameters.
● error: result code.
● error_description: error description.
Sample code:
HTTP/1.1 400 Bad Request
Content-Type: application/json
Cache-Control: no-store
{
"error": "1102",
"error_description": " The request is missing a required parameter"
}
The default validity period of an access token is 3600 seconds. When the access token expires, you need to use the refresh token to obtain a new access token. To obtain a new access token using the refresh token, go to Step 5.
5. Call the API for obtaining a new access token using the refresh token.The validity period of a refresh token is six months. If the refresh token has expired, go to Step 3.
To obtain a new access token using the refresh token, send a request using the POST method from the app's server to the Huawei OAuth 2.0 authorization service address https://login.cloud.huawei.com/oauth2/v2/token with the following parameters:
● grant_type: This parameter is mandatory and has a fixed value of refresh_token.
● refresh_token: refresh token used to obtain a new access token. This parameter is mandatory.
● client_id: app ID obtained when you create an app on HUAWEI Developer. This parameter is mandatory.
● client_secret: app secret obtained when you create an app on HUAWEI Developer. This parameter is mandatory.
Sample code:
POST /oauth2/v2/token HTTP/1.1
Host: login.cloud.huawei.com
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&client_id=12345&client_secret=bKaZ0VE3EYrXaXCdCe3d2k9few&refresh_token=2O9BSX675FGAJYK92KKGG
Caution:
Input parameters must be urlencoded.
If there are no errors in the request, the authentication server will send a JSON string consisting of the following parameters:
● access_token: new access token to be obtained. If an access_token contains backslashes (\), remove all of them.
● expires_in: validity period of the access token, in seconds.
● refresh_token: refresh token used to obtain a new access token. The refresh token has a validity period of six months and is returned only for some apps.
● scope: list of permissions granted by the user.
Sample code:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
{
"access_token": "346346sdxcdfsa3566546dfdfgfg=",
"expires_in": 3600,
"refresh_token": "68dieddfg08349786gdgfsdfa=",
"scope": "email",
}
If there are errors in the request, the authentication server will send a JSON string consisting of the following parameters.
● error: result code.
● error_description: error description.
HTTP/1.1 400 Bad Request
Content-Type: application/json
Cache-Control: no-store
{
"error": "1102",
"error_description": "The request is missing a required parameter "
}
6. Call the getaccountinfo API with the access token to obtain HUAWEI ID information of the user from Huawei server, including the user name, OpenID, and avatar. To obtain union_id, call the getTokenInfo API.
Debugging HUAWEI Account Kit
1. Start Huawei quick app IDE.
2. Copy the formal certificate file from the release folder under the sign directory of the project to the debug folder.
3. Choose Build > Run Build to debug the app.
If an exception occurs, perform the following operations to locate the fault:
1. Check whether you have applied for a Huawei ID from HUAWEI Developer. For details, please refer to Applying for HUAWEI Account Kit.
2. Call the account.getProvider API to obtain the service provider information. Ensure that the return value is huawei before invoking other APIs. For details about APIs related to HUAWEI Account Kit, please refer to API > Huawei Services > Account.
3. If the result code 1002 is returned, check whether the signature generated by Huawei quick app IDE is consistent with the certificate fingerprint configured on HUAWEI Developer, and whether the formal certificate file in the release folder under the sign directory of the project is copied to the debug folder.
4. Rectify the fault according to the following result code description.
Result CodeDescriptionSuggestion200Common error. The error is usually caused by a gateway request network error. For details, check the error message.If the status code 403 is displayed, switch the network or check whether the scope parameter has been passed.201The user refused to authorize.202Incorrect input parameter.Verify the input parameters.1002Failed to verify the signature.Check whether the RPK is of a formal build version and whether the signature is the same as that configured on HUAWEI Developer.OthersPlease refer to the result codes in Common Result Codes.
FAQ
Q: What can I do if I cannot access my Huawei ID?
The Huawei ID interface is customized by the vendor. To facilitate fault location, install the Huawei Quick App IDE for debugging.
If an exception occurs, perform the following operations to locate the fault:
Check whether you have applied for a Huawei ID to HUAWEI Developer. For details, see Applying for HUAWEI Account Kit.
Invoke the account.getProvider interface. Ensure that the return value ishuaweibefore invoking other interfaces. For details about interfaces related to Huawei IDs, see API > Huawei Mobile Service > Account.
If the error code 1002 is displayed, check whether the signature information generated by the IDE is consistent with the certificate fingerprint configured on HUAWEI Developer. If you debug aquickapp underBuild>RunBuild, copy the formal certificate file from thereleasefolder in thesigndirectory of the IDE project to thedebugfolder.
If other error codes are displayed, rectify the fault by referring to "HMSSDK Framework Error Codes" in Common Error Codes about Huawei accounts.
For details about Huawei developers and HMS, visit the website.
HUAWEI Developer Forum | HUAWEI Developer
forums.developer.huawei.com
Symptom
When you enter a value in the input box and submit it, the mandatory item verification fails, and the system displays a message indicating that xxx is empty and instructs you to enter a value.
Cause Analysis
The possible cause is that the method for obtaining the value is incorrect. As a result, the value in the input box cannot be obtained.
The code for obtaining the input value is as follows:
e.target.attr.value, this.$element('#id').attr.value.
Solution
Use the onchange event to assign a value to the model and obtain the value of the input box. The method is as follows:
1. Initialize the model.
1
2
31. data:{
2. accountValue:''
3. }
2. Bind an event to the input box.
1. <input @change="getAccountValue" value="{{accountValue}}"></input>
3. Assign a value.
1. getAccountValue: function(e) {
2. this.accountValue = e.value // Here, e.value instead of e.target.attr.value is used.
3. }
Suggestions and Summary
Refer to the official document instead of generating a JavaScript object for coding. A JavaScript object may lead to compatibility issues.
Currently, the data binding mode of the quick app is unidirectional.
1. The value entered in the input box does not change the value of accountValue in data.
2. If the value of the input box is changed by setting this.accountValue to xxx, the onchange event of the input will not be triggered.
3. In this.accountValue = xxx format, if the value of accountValue before and after the change is the same, the page will not be re-rendered.
For details about Huawei developers and HMS, visit the website.
HUAWEI Developer Forum | HUAWEI Developer
forums.developer.huawei.com
SymptomThe data returned by the fetch request in the code is a JSON character string by default and the logic of parsing JSON objects is used.
Once the server permission verification fails, an HTML page with error code 503 may be returned, meaning the JSON parsing logic is not suitable.
SolutionSolution 1: Add try-catch to each place where JSON.parse() is executed to capture and handle errors.
Solution 2: Process JSON.parse() in the app.ux file in advance and add try-catch to the code. Record event tracing data or return the default normal data when an exception occurs.
Solution 2 is recommended and the sample code is as follows:
Code:
export function parseProxy () {
const rawParse = JSON.parse
JSON.parse = function (str, defaults) {
try {
return rawParse(str)
}
catch (err) {
console.error(`JSON parsing failure:${str}, ${err.stack}`)
return defaults
}
}
}
after adding try-catch does it parse JSON data or does it just handles the crash part?