HMS Core location Kit TypeError: Cannot read properties of undefined (reading 'getFusedLocationProviderClient') - Ionic/Capacitor - VueJS - javascript

I'm trying to implement HMS Core location kit into my vue ionic app.
I import HMSLocation and declare it, but when I try to use the getFusedLocationProviderClient function I get
TypeError: Cannot read properties of undefined (reading 'getFusedLocationProviderClient')
import { HMSLocation } from "#hmscore/ionic-native-hms-location/ngx";
export default {
data() {
return {
hmsLocation: null,
fusedClient: null,
locationResult: null,
};
},
mounted() {
this.getLocation();
},
methods: {
async getLocation() {
this.hmsLocation = new HMSLocation();
console.log(this.hmsLocation);
this.fusedClient = this.hmsLocation.getFusedLocationProviderClient();
this.locationResult = await this.fusedClient.getLastLocation;
},
},
.....
console.log(this.hmsLocation); returns
node_modules/#hmscore/ionic-native-hms-location/ngx
import { IonicNativePlugin } from '#ionic-native/core';
export declare class HMSLocation extends IonicNativePlugin {
getGeofenceService(): GeofenceService;
getGeocoderService(language: string, country?: string): GeocoderService;
getFusedLocationProviderClient(): FusedLocationService;
getActivityIdentificationService(): ActivityIdentificationService;
addListener(event: Events, callback: (data: LocationResult | [] | ActivityConversionResponse | ActivityIdentificationResponse) => void): any;
disableLogger(): Promise<void>;
enableLogger(): Promise<void>;
}
export declare class BackgroundManager {
private constructor();
static notify(notificationId: number, notification: string): void;
static makeToast(text: string, duration: number): void;
}
export interface FusedLocationService {
disableBackgroundLocation(): Promise<void>;
enableBackgroundLocation(notificationId: number, notification: string): Promise<void>;
checkLocationSettings(request: LocationSettingsRequest): Promise<LocationSettingsStates>;
flushLocations(): Promise<void>;
getLastLocation(): Promise<Location>;
getLastLocationWithAddress(request: LocationRequest): Promise<HWLocation>;
getLocationAvailability(): Promise<boolean>;
getNavigationContextState(requestType: NavigationRequestConstants): Promise<NavigationResult>;
removeLocationUpdates(requestCode: number, type: RequestType): Promise<boolean>;
requestLocationUpdates(requestCode: number, request: LocationRequest, callback?: (locationResult: LocationResult) => void): Promise<boolean>;
requestLocationUpdatesEx(requestCode: number, request: LocationRequest): Promise<boolean>;
setMockLocation(latLng: LatLng): Promise<void>;
setMockMode(mode: boolean): Promise<void>;
setLogConfig(logConfigSettings: LogConfigSettings): Promise<void>;
getLogConfig(): Promise<LogConfigSettings>;
}

Related

React Typescript interface

I get a problem when making an interface on Typescript!
export interface Content {
uuid?: string;
brand_id?: string;
brand_name?: string;
is_active?: boolean;
}
export interface Pageable {
sort?: Sort;
pageSize?: number;
pageNumber?: number;
offset?: number;
unpaged?: boolean;
paged?: boolean;
}
export interface Sort {
sorted?: boolean;
unsorted?: boolean;
empty?: boolean;
}
export interface BrandData {
content?: Content;
pageable?: Pageable;
numberOfElements?: number;
number?: number;
sort?: Sort;
size?: number;
first?: boolean;
last?: boolean;
empty?: boolean;
}
export interface BrandResponse {
readonly data?: BrandData[];
}
and then i want to get data in react component like this
const { brands } = useSelector((state: AppState) => state.catalogs.brands);
const [brandData, setBrandData] = React.useState(brands.data);
const [currentPage, setCurrentPage] = React.useState(brandData.pageable.pageNumber);
then the error exits like this
Property 'pageable' does not exist on type 'BrandData[]'.

Vue 3 TypeScript - Property 'searchData' does not exist on type 'CreateComponentPublicInstance

im trying to use function as a computed value in defineComponent:
code printscreen
<script lang="ts">
import { defineComponent } from "#vue/runtime-core";
import { testData } from "../assets/testData";
export type SearchDataType = {
_id: string;
index: number;
name: string;
};
interface ISearchPage {
searchData: SearchDataType[];
searchQuery: string
}
export default defineComponent({
name: "SearchPage",
components: {},
data(): ISearchPage {
return {
searchData: [],
searchQuery: ''
};
},
methods: {
getData: function () {
this.searchData = testData;
},
},
created(){
this.getData()
},
computed: {
filteredSearch: function() {
return this.searchData.filter((filteredItem: SearchDataType) => {
return filteredItem.name.match(this.searchQuery)
})
}
}
});
</script>
And, when i want to use this.searchData variable in computed im reciving the following errors:
Property 'searchData' does not exist on type 'CreateComponentPublicInstance<{ [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: undefined; }, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, ... 10 more ..., {}>'.
Property 'searchData' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $props: { [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: undefined; }; ... 10 more ...; $watch(source: string | Function, cb: Function, options?: WatchOptions<...> | undefined): WatchStopHandle; } & ... 4 more ... & Co...'
I was trying to add the code below to shims-vue.d.ts file, but it didn't solve the problem:
import { ComponentCustomProperties } from "vue";
declare module "#vue/runtime-core" {
interface CreateComponentPublicInstance {
searchData: any | null;
}
}
Im new to vue with TypeScript. Could someone tell me, what am doing wrong?

React overload on Typescript - CombineReducer

I am currently using a redux pattern in a create-react-app with typescript.
Currently i am having an issue deciphering the overload error messages.
The current fix works but i dont think its correct as it wont be strictly typed anymore.
const combinedReducers = combineReducers({ reducer1, reducer2 } as any);
Overload Error message:
No overload matches this call.
Overload 1 of 3, '(reducers: ReducersMapObject<ApplicationState, any>): Reducer<CombinedState<ApplicationState>, AnyAction>', gave the following error.
Type '(state: ModelState | undefined, action: any) => { model: any; loading: boolean; errorMessage: string; } | { loading: boolean; errorMessage: any; model: never[]; }' is not assignable to type 'Reducer<ModelState, any>'.
Type '{ model: any; loading: boolean; errorMessage: string; } | { loading: boolean; errorMessage: any; model: never[]; }' is not assignable to type 'ModelState'.
Type '{ loading: boolean; errorMessage: any; model: never[]; }' is not assignable to type 'ModelState'.
Types of property 'model' are incompatible.
Type 'never[]' is missing the following properties from type 'Model': opportunity_id, model_result TS2769
24 | save_opportunity_state: SaveOpportunityReducer,
25 | archive_state: ArchiveOpportunityReducer,
> 26 | model_state: GetModelReducer,
| ^
27 | });
28 |
Reducer:
export interface ModelState {
model: Model;
loading: boolean;
errorMessage: string;
}
export interface Model {
opportunity_id: string;
model_result: ModelResult;
}
export interface ModelResult {
model_info: ModelInfo;
qualification: Qualification;
similar_deals?: null[] | null;
tool_tips: ToolTips;
top_actions?: null[] | null;
win_probability: WinProbability;
}
export interface ModelInfo {
probability_version: string;
similar_deals_version: string;
}
export interface Qualification {
colour: string;
score: number;
}
export interface ToolTips {
[key: string]: string;
}
export interface WinProbability {
colour: string;
features?: null[] | null;
score: number;
}
const initialState: ModelState = {
model: {
opportunity_id: '',
model_result: {
model_info: { probability_version: '', similar_deals_version: '' },
qualification: { colour: 'grey', score: 0 },
similar_deals: [],
tool_tips: {},
top_actions: [],
win_probability: { colour: 'green', features: [], score: 0 },
},
},
loading: false,
errorMessage: '',
};
If you look at the error message, specifically the last one states that model is missing following property.
I am guessing your failure case just returns an empty object. This contradicts the types defined above as the model should always contain x, y and z.
So in your failure case, you should add the following:
model: { ...initialState.model },

Extending Interface/types in typescript

I have extended my FilterMetaData type to add a dynamic model which is different structure for different entities but somehow typescript not recognizing my object properties. I might be missing something here.
Interfaces
export type FilterMetaData<T extends {}> = T & {
filterCriteriaID: number;
filterCriteriaName?: string;
isDefaultSelected?: boolean;
isExpanded?: boolean;
}
export interface DateRange {
data?: DateRangeData;
}
export interface DateRangeData {
min?: Date;
max?: Date;
}
export interface Range {
data?: RangeData;
}
export interface RangeData {
currency?: string;
timePeriod?: string;
min?: number;
max?: number;
step?: number;
}
export interface Select {
data?: SelectData[];
}
export interface SelectData {
id?: number;
name?: string;
isSelected?:boolean|false;
parentID?: number | null;
parentName?: string;
}
Implementation in class
helper<T1 extends FilterMetaData<T2>>(filter) {
this.selectedFilterService.getAppliedFilterMasterData<T1>(filter)
.pipe(takeUntil(this.unsubscribe$))
.subscribe((filterData: T1) => {
if (filter.isDefaultSelected) {
filterData.isExpanded = false;
filterData.data.forEach((data) => data.isSelected = false);
this.selectedFilters.result.select.push(filterData);
this.loadComponent(new FilterComponentType(SelectComponent, filterData));
} else {
this.removeComponent(filter);
}
}, err => {
this.toastrService.error(err);
})
}
Invoking Function with type args like this:--
this.helper<FilterMetaData<Select>>(filter);

MediaStreamRecorder is not a constructor

I'm new to Angular6 and I'm trying to use MediaStreamRecorder. I'm definitely doing something wrong when defining MediaStreamRecorder because I keep getting the error TypeError: msr__WEBPACK_IMPORTED_MODULE_4__.MediaStreamRecorder is not a constructor. Not sure how or where should I declare and define MediaStreamRecorder. Can you help me with this, please?
I have installed msr module, and my code looks like this:
import { Component,ViewChild, OnInit, Inject } from '#angular/core';
import { LinksService } from 'demo/_services/links.service';
import { Http,Response,Headers } from '#angular/http';
import { MediaStreamRecorder} from 'msr';
import { RecordRTC } from 'recordrtc';
#Component({
selector: 'demo-ceva',
templateUrl: './ceva.component.html',
styleUrls: ['./ceva.component.css'],
providers: [
{
provide: SpeechRecognitionLang,
useValue: 'en-US',
},
SpeechRecognitionService,
],
})
export class CevaComponent {
public navigator: any;
public MediaStreamRecorder: any;
constructor( private http: Http, private service: SpeechRecognitionService, private links: LinksService ) {
this.record = () => {
var browser = <any>navigator;
var obj = { audio: true, video:false };
browser.getUserMedia = (browser.getUserMedia || browser.webkitGetUserMedia || browser.mozGetUserMedia || browser.msGetUserMedia);
browser.mediaDevices.getUserMedia(obj).then(stream => {
var source = window.URL.createObjectURL(stream);
var config= { ... }
var recorder = new MediaStreamRecorder(stream, config);
recorder.record();
recorder.stop(function(blob) {
var blob = recorder.blob;
console.log(blob);
});
});
});
As the answer to this post suggested, the solution to me was that in typings.d.ts file to add the following declarations:
declare interface MediaRecorderErrorEvent extends Event {
name: string;
}
declare interface MediaRecorderDataAvailableEvent extends Event {
data : any;
}
interface MediaRecorderEventMap {
'dataavailable': MediaRecorderDataAvailableEvent;
'error': MediaRecorderErrorEvent ;
'pause': Event;
'resume': Event;
'start': Event;
'stop': Event;
'warning': MediaRecorderErrorEvent ;
}
declare class MediaRecorder extends EventTarget {
readonly mimeType: string;
// readonly MimeType: 'audio/wav';
readonly state: 'inactive' | 'recording' | 'paused';
readonly stream: MediaStream;
ignoreMutedMedia: boolean;
videoBitsPerSecond: number;
audioBitsPerSecond: number;
ondataavailable: (event : MediaRecorderDataAvailableEvent) => void;
onerror: (event: MediaRecorderErrorEvent) => void;
onpause: () => void;
onresume: () => void;
onstart: () => void;
onstop: () => void;
constructor(stream: MediaStream);
start();
stop();
resume();
pause();
isTypeSupported(type: string): boolean;
requestData();
addEventListener<K extends keyof MediaRecorderEventMap>(type: K, listener: (this: MediaStream, ev: MediaRecorderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof MediaRecorderEventMap>(type: K, listener: (this: MediaStream, ev: MediaRecorderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
And in my component, I was able to use var mediaRecorder = new MediaRecorder(stream); without any other declarations. Thank you, #firegloves , for the link to this post and thank you, #Tiberiu C. for the answer! It was really helpful.
npm install -D #types/dom-mediacapture-record
I had the same issue with pure JS and React and removing the following line "fixed" the problem:
window.MediaRecorder = require('audio-recorder-polyfill');

Categories

Resources