How do i stop music player when app is minimized and keep it checked on loop
so I'm not sure if I should call this loop but is there a way to keep checking if app is minimized and then stop the music, and once app is resumed the music should continue. I am doing this with Intervals inside of NgOnInit
It looks like this
ngOnInit(){
setInterval(() => {
document.addEventListener("pause", () => {
this.isPlaying = false;
this.player.stop();
}, false);
document.addEventListener("resume", () => {
this.isPlaying = false;
this.player.stop();
}, false);
})
}
But I am pretty sure this is the wrong way of doing it, I can't do it in another component though because the music stop function is in this one. Can anyone help me do it? This is working btw when I minimize the music is stopped but it does not resume once the app is reopened.
Also how do you loop stuff in Angular I really do not get it, is there not a main function that you can put stuff like this in to check for entire project without having to click buttons?
See also questions close to this topic
-
Firebase Cloud function in expo project
So I have a cloud function (this is not in the react native app directory yet):
const admin = require('firebase-admin'); const firebase_tools = require('firebase-tools'); const functions = require('firebase-functions'); admin.initializeApp(); exports.deleteUser = functions .runWith({ timeoutSeconds: 540, memory: '2GB' }) .https.onCall((data, context) => { const userId = context.auth.uid; var promises = []; // DELETE DATA var paths = ['users/' + userId, 'messages/' + userId, 'chat/' + userId]; paths.forEach((path) => { promises.push( recursiveDelete(path).then( () => { return 'success'; } ).catch( (error) => { console.log('Error deleting user data: ', error); }) ); }); // DELETE FILES const bucket = admin.storage().bucket(); var image_paths = ["avatar/" + userId, "avatar2/" + userId, "avatar3/" + userId]; image_paths.forEach((path) => { promises.push( bucket.file(path).delete().then( () => { return 'success'; } ).catch( (error) => { console.log('Error deleting user data: ', error); }) ); }); // DELETE USER promises.push( admin.auth().deleteUser(userId) .then( () => { console.log('Successfully deleted user'); return true; }) .catch((error) => { console.log('Error deleting user:', error); }) ); return Promise.all(promises).then(() => { return true; }).catch(er => { console.error('...', er); }); }); function recursiveDelete(path, context) { return firebase_tools.firestore .delete(path, { project: process.env.GCLOUD_PROJECT, recursive: true, yes: true, token: functions.config().fb.token }) .then(() => { return { path: path } }).catch( (error) => { console.log('error: ', error); return error; }); } // [END recursive_delete_function]
This is used for my swift app. How Can I use this for my react native app built with Expo?
I have installed the following
yarn add @react-native-firebase/functions
I have my firebase.js file set up in the root directory:
import * as firebase from "firebase"; // Your web app's Firebase configuration var firebaseConfig = { apiKey: "test", authDomain: "test", databaseURL: "test", projectId: "test", storageBucket: "test", messagingSenderId: "test", appId: "test" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); export default firebase;
I have a button:
<Text>Delete Account</Text> <View> <Button title="Delete Account" color="#F9578E" accessibilityLabel="Delete Account" /> </View>
Which when clicked signs the user out and runs the above cloud function.
-
Cleaner, better way to pass function callback and state to a child component in React?
Right now I am passing a callback function and the current state to a child component from my Parent component. I just feel like the way I write it is ugly or at least could be prettier. Here is the Parent component where I am passing all that (
parentCallback={[moreReviews, limit]}
in the return):const Reviews: FunctionComponent = () => { const [filter, setFilter] = useState([1, 2, 3, 4, 5]); const [order, setOrder] = useState('date_desc'); const [reviews, setReviews] = useState([]); const [limit, setLimit] = useState(1); let variables = { offset: 0, limit: limit, filter: filter, order: order } const {data: dataReviews, loading: loadingReviews, error: errorReviews} = useQuery(GetReviews, { ssr: false, variables: variables, fetchPolicy: "no-cache" }); useEffect(() => { console.log('action going on deps change'); if (!loadingReviews && !errorReviews && dataReviews) { setReviews(!loadingReviews && !errorReviews && dataReviews ? dataReviews.reviews[0].reviews : []); } }, [dataReviews]); function moreReviews(limit: number) { setLimit(limit); } return reviews.length ? ( <div> <div className={`${styles.netreviews_review_rate_and_stars}`}> <ReviewsSideInfo/> <ReviewsContainer reviews={reviews} parentCallback={[moreReviews, limit]} /> </div> </div> ) : <div/>; }; export default Reviews;
And then in my child component I'm accessing it like so :
<button onClick={() => parentCallback[0](parentCallback[1] + 1)}></button>
That is definitely ugly but its working fine.
Also, and probably more importantly, is a better, more efficient way to do that, from a technical point of view ? Thanks
-
Django load text file into html file using jquery
I want to implement this example code from w3schools.com using Django. The code loads a text file into a html file using the jquery
load()
function. The code looks like this<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").load("demo_test.txt"); }); }); </script> </head> <body> <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div> <button>Get External Content</button> </body> </html>
My question is now, how do I store my text file such that the load function has access to it in my Django project?
-
Ionic5 angular11 page reach dont display at first flow then display when re-doing. loading or routing issue? your help please
please help me :) Thanks in advance !! My app is Tab based. When starting, the first page on first tab (pollListing) shows: Users list (all users) + a list of Polls (created by so called users). As you could guess, click on poll will open the poll details page click on user reaches user profile page which includes user profile + list of polls created by this specific user, and if you click on poll then it goes to poll details page.
Now the issue: If I do: Home => Click on User => View User profile => click on poll => [POLL DETAIL VIEW NOT DISPLAYED]!! (full white screen) !important note: the URL keeps being the same as original tab while I would expect the URL of the page/components along the way THEN I navigate to another tab (create Poll) (as I cannot come back directly on the home tab (pollListing) as the URL still consider I am on that page...) THEN I go back to the 1st tab (pollListing) and redo the flow => click on User => View User Profile => Click on poll => NOW THE POLL DETAILS PAGE WORKS AND DISPLAYS DETAILS and of course on that flow the URL are correctly updated along the way.
So to recap that one: PollListing => User Profile => Poll-detail [FAILS TO DISPLAY] => poll-creation (other tab other tab just to be able to out) => PollListing => User Profile-view => Poll-detail NOW IT WORKS (I guess because it loaded data properly on first attempt and this time works fine)
Other funny thing, if I start by displaying the poll-details from pollLIsting, then go to profile and "re-display" from profile IT WORKS
in short: PollListing => poll-detail (pollA) => poll-creation (other tab just to be able to out) => PollListing => User Profile-view => poll-detail (pollA) IT WORKS
I suspect a lifecycle or routing handling issue - but I am too newbie to figure out it seems :( or maybe it s something totally different.
My code looks like as follow:
Tab routing (dont think it's relevant but just in case)
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { TabsPage } from './tabs.page'; const routes: Routes = [ { path: 'tabs', component: TabsPage, children: [ { path: 'pollListing', loadChildren: () => import('../pollListing/pollListing.module').then(m => m.pollListingPageModule) }, { path: 'createPoll', loadChildren: () => import('../createPoll/createPoll.module').then(m => m.createPollPageModule) }, { path: 'tab3', loadChildren: () => import('../tab3/tab3.module').then(m => m.Tab3PageModule) }, { path: 'tab4', loadChildren: () => import('../tab4/tab4.module').then(m => m.Tab4PageModule) }, { path: 'poll-detail', loadChildren: () => import('../poll-detail/poll-detail.module').then( m => m.PollDetailPageModule) }, { path: 'poll-detail/:pollID', loadChildren: () => import('../poll-detail/poll-detail.module').then( m => m.PollDetailPageModule) }, { path: 'profile-view/:profileID', loadChildren: () => import('../profile-view/profile-view.module').then( m => m.ProfileViewPageModule) } ] }, { path: '', redirectTo: '/tabs/pollListing', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forChild(routes)], }) export class TabsPageRoutingModule {}
then the poll listing ts (routing/module untouched) - basically it calls 2 APIs to get Users and Polls. Polls are displayed with infinite scroll
import { Component } from '@angular/core'; import { HttpConfigService } from '../services/http-config.service'; @Component({ selector: 'app-pollListing', templateUrl: 'pollListing.page.html', styleUrls: ['pollListing.page.scss'] }) export class pollListingPage { uid = "alpha" url: string; url2: string; itemListData = []; itemListFollowsData = []; page_number = 1; page_limit = 30; constructor( private httpConfigService: HttpConfigService ) {} ngOnInit() { this.getFollowedProfiles(); this.getPolls(false, ""); } getPolls(isFirstLoad, event) { this.url = '?pollText=a?_page=' + this.page_number + '&_limit=' + this.page_limit; this.httpConfigService.getListItems(this.url) .subscribe((data: any) => { for (let i = 0; i < data.length; i++) { this.itemListData.push(data[i]); } if (isFirstLoad) event.target.complete(); scrollLength = data.length; this.page_number++; }, error => { console.log(error); }) } doInfinite(event) { this.getPolls(true, event); } getFollowedProfiles() { this.url2=this.uid; this.httpConfigService.getFollowed(this.url2) .subscribe((dataF: any) => { for (let i = 0; i < dataF.length; i++) { this.itemListFollowsData.push(dataF[i]); } // if (isFirstLoad) // event.target.complete(); // this.page_number++; }, error => { console.log(error); }) } }
the html of pollisting - users are in a row, polls are a list with infinite scroll and routerlink to then reach them
<ion-content [fullscreen]="true"> <!-- Story line --> <ion-list class="story" scrollX="true"> <div class="story_scroll" *ngFor="let F of itemListFollowsData"> <div class="story_img_bg"> <img no-margin no-padding class="story_img" [src]="F.avatar" [routerLink]="['/tabs/profile-view/' + F.uid]" [routerDirection]="forward"></div> <p no-margin no-padding text-center class="story_text">{{ F.profileName }}</p> </div> </ion-list> <ion-list> <ion-item *ngFor="let poll of itemListData" [routerLink]="['/tabs/poll-detail/' + poll.uid]" > <ion-avatar slot="start"> <img [src]="poll.imageUrl" [alt]="NoPi"> </ion-avatar> <ion-label> <ion-text> <h3> {{poll.uid}} {{poll.count}} Respondants</h3> </ion-text> <ion-text color="medium"> <p>{{poll.text}}</p> </ion-text> </ion-label> </ion-item> </ion-list> <ion-infinite-scroll (ionInfinite)="doInfinite($event)" on-infinite="moreElements()"> <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data..."> </ion-infinite-scroll-content> </ion-infinite-scroll> </ion-content>
the ts of profile-view - profile view is 2 API calls, 1 for user profile data, 1 for polls created by this user. inifinite scrolls for polls.
import { Component, OnInit, AfterViewInit } from '@angular/core'; import { HttpConfigService } from '../services/http-config.service'; import { ActivatedRoute, Router } from '@angular/router'; import { NavController } from '@ionic/angular'; @Component({ selector: 'app-profile-view', templateUrl: './profile-view.page.html', styleUrls: ['./profile-view.page.scss'], }) export class ProfileViewPage implements OnInit { profileID = "alpha"; ProfileData = []; CreatedPolls =[]; numberPolls = 0; url: string; page_number = 1; page_limit = 30; constructor( private route : ActivatedRoute, private httpConfigService: HttpConfigService ) { } ngOnInit() { this.profileID = this.route.snapshot.paramMap.get('profileID'); this.getUserProfile(); this.getUserCreatedPolls(false, ""); } getUserProfile() { this.httpConfigService.getProfile(this.profileID) .subscribe((dataProfile: any) => { for (let i = 0; i <= dataProfile.length; i++) { this.ProfileData.push(dataProfile[i]); } }, error => { console.log(error); }) } getUserCreatedPolls(isFirstLoad, event) { this.url= this.profileID +'/?_page=' + this.page_number + '&_limit=' + this.page_limit; this.httpConfigService.getCreatedPolls(this.url) .subscribe((dataCreated: any) => { this.numberPolls = dataCreated.length; for (let i = 0; i <= dataCreated.length; i++) { this.CreatedPolls.push(dataCreated[i]); } if (isFirstLoad) event.target.complete(); this.page_number++; }, error => { console.log(error); }) } doInfinite(event) { this.getUserCreatedPolls(true, event); } }
the html of profile-view, basically one item with profile avatar and details, and then list of polls created by the user with routerlink to reach them.
<ion-content> <ion-item > <ion-avatar slot="start"> <img [src]="ProfileData[0].avatar"> </ion-avatar> <ion-label> <ion-text> <h3> {{ProfileData[0].profileName}} </h3> <!-- <h3> {{profiled.profileName}} followers: {{FollowerssData.length}} Follows: {{FollowsData.length}}Respondants</h3> --> </ion-text> <ion-text color="medium"> <p>{{ProfileData[0].description}}</p> </ion-text> <ion-text color="medium"> <p>Polls Created: {{numberPolls}}</p> </ion-text> </ion-label> </ion-item> <ion-list> <ion-item *ngFor="let Userpoll of CreatedPolls" [routerLink]="['/tabs/poll-detail/' + Userpoll.uid]" [routerDirection]="forward"> <ion-avatar slot="start"> <img [src]="Userpoll.imageUrl"> </ion-avatar> <ion-label> <ion-text> <h3> {{Userpoll.uid}} {{Userpoll.count}} Respondants</h3> </ion-text> <ion-text color="medium"> <p>{{Userpoll.text}}</p> </ion-text> </ion-label> </ion-item> </ion-list> <ion-infinite-scroll (ionInfinite)="doInfinite($event)"> <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data..."> </ion-infinite-scroll-content> </ion-infinite-scroll> </ion-content>
and ts of poll-detail (which is called from pollListing or from profile-view via routerLink), this is 1 API call to get the details + 1API call to get possible answers.
import { Component, OnInit, AfterViewInit } from '@angular/core'; import { HttpConfigService } from '../services/http-config.service'; import { PollModel } from '../models/pollmodel'; import { ActivatedRoute, Router } from '@angular/router'; import { NavController } from '@ionic/angular'; import { Pollanswers } from '../models/pollanswers'; import { Pollresponse} from '../models/pollresponse'; @Component({ selector: 'app-poll-detail', templateUrl: './poll-detail.page.html', styleUrls: ['./poll-detail.page.scss'], }) export class PollDetailPage implements OnInit { uid: string; pollID: any; dataPollDetail: PollModel; dataPollAnswers: Pollanswers[]; dataPollResponse: Pollresponse; data: any; data2: string; //responsecapture: string; constructor( private navCtrl: NavController, private router: Router, private route : ActivatedRoute, private httpConfigService: HttpConfigService ) { this.dataPollResponse = new Pollresponse(); } ngOnInit() { this.pollID = this.route.snapshot.paramMap.get('pollID'); this.httpConfigService.getPoll(this.pollID).subscribe(response => { console.log(response); this.dataPollDetail = response; this.httpConfigService.getPollAnswers(this.pollID).subscribe(response2 => { console.log(response2); this.dataPollAnswers = response2; this.data2= JSON.stringify(this.dataPollAnswers) }); }); } ionViewWillEnter () { //window.location.reload(); this.pollID = this.route.snapshot.paramMap.get('pollID'); this.httpConfigService.getPoll(this.pollID).subscribe(response => { console.log(response); this.dataPollDetail = response; this.httpConfigService.getPollAnswers(this.pollID).subscribe(response2 => { console.log(response2); this.dataPollAnswers = response2; this.data2= JSON.stringify(this.dataPollAnswers) }); }); } submitResponse(responsecapture) { //this.dataPollResponse.profileId = "beta"; this.dataPollResponse.pollId = this.pollID; this.dataPollResponse.response = responsecapture; this.httpConfigService.addResponse(this.dataPollResponse).subscribe((res:any) => { }); } }
and the associated html - displays details in multiple items and buttons reflecting available options
<ion-header> <ion-toolbar color="tertiary"> <ion-title>pollDetail</ion-title> </ion-toolbar> </ion-header> <ion-content [fullscreen]="true"> <ion-item lines="full"> <ion-label mode= "ios" position="floating">profile ID alpha ou beta</ion-label> <ion-input [(ngModel)]="dataPollResponse.profileId" name="profileId"></ion-input> </ion-item> <ion-item> <ion-label>Created: </ion-label><br> <ion-label color= "tertiary" side= "left"> {{dataPollDetail.created}}</ion-label> </ion-item> <ion-item> <ion-label>Poll Question: </ion-label><br> <ion-label color= "tertiary" side= "left"> {{dataPollDetail.text}}</ion-label> </ion-item> <ion-item> <ion-label>Additional information: </ion-label><br> <ion-label color= "tertiary" side= "left"> {{dataPollDetail.details}}</ion-label> </ion-item> <ion-item> <ion-label>weblink: </ion-label><br> <ion-label color= "success" side= "left"> {{dataPollDetail.weblink}}</ion-label> </ion-item> <ion-button *ngIf="dataPollAnswers.ans1 != null" (click)="submitResponse(dataPollAnswers.ans1)" [routerLink]="['/tabs/poll-results/' + dataPollDetail.uid]" [routerDirection]="forward" color="success" size="small"> {{dataPollAnswers.ans1}} </ion-button> <ion-button *ngIf="dataPollAnswers.ans2 != null" (click)="submitResponse(dataPollAnswers.ans2)" [routerLink]="['/tabs/poll-results/' + dataPollDetail.uid]" [routerDirection]="forward" color="danger" size="small"> {{dataPollAnswers.ans2}} </ion-button> <ion-button *ngIf="dataPollAnswers.ans3 != null" (click)="submitResponse(dataPollAnswers.ans3)" [routerLink]="['/tabs/poll-results/' + dataPollDetail.uid]" [routerDirection]="forward" color="success" size="small"> {{dataPollAnswers.ans3}} </ion-button> <ion-button *ngIf="dataPollAnswers.ans4 != null" (click)="submitResponse(dataPollAnswers.ans4)" [routerLink]="['/tabs/poll-results/' + dataPollDetail.uid]" [routerDirection]="forward" color="danger" size="small"> {{dataPollAnswers.ans4}} </ion-button> <ion-button *ngIf="dataPollAnswers.ans5 != null" (click)="submitResponse(dataPollAnswers.ans5)" [routerLink]="['/tabs/poll-results/' + dataPollDetail.uid]" [routerDirection]="forward" color="success" size="small"> {{dataPollAnswers.ans3}} </ion-button> <ion-button *ngIf="dataPollAnswers.ans6 != null" (click)="submitResponse(dataPollAnswers.ans6)" [routerLink]="['/tabs/poll-results/' + dataPollDetail.uid]" [routerDirection]="forward" color="danger" size="small"> {{dataPollAnswers.ans4}} </ion-button> </ion-content>
Thanks for your help :)
-
How do I convert JavaScript code to Typescript code
I have a huge JavaScript project with over 10000 lines which is a open source project. I am trying it to make it as a angular project so now I need to convert it to Typescript as fast as I can. I tried some npm libraries also to convert them but they did nothing.So somebody help me through how to convert js to ts. Thank you.
- Material Input Crops Input top and bottom
-
How to dynamically add a new property while updating the draft on immer?
Consider the following code, where line 2 fails with
Property 'newProperty' does not exist on type 'WritableDraft<MyObject>'. TS7053
// data is of type MyObject which until now has only a property myNumber const payload = produce(data, (draft) => { draft['newProperty'] = 'test'; // Property 'newProperty' does not exist on type 'WritableDraft<MyObject>'. TS7053 });
How can I dynamically add a new property to the draft or change the type of the draft to a type which already includes the
newProperty
? I do not want to havenewProperty
in theMyObject
type itself. -
How to import a single-spa in-browser utility module into a TypeScript parcel project
I have 3 TypeScript projects below:
- root-config
- parcel, let us call it
my-app
- in-browser utility module, let us call it
api
All the projects above were generated using the
create-single-spa
command.In the
api/src/lomse-api.ts
file, I'm exporting thefetchPeople
module as shown below:export { fetchPeople } from "./PeopleApi.ts";
According to the single-spa documentation, given my
orgName
islomse
andprojectName
isapi
, I should be able to import thefetchPeople
module intomy-app
(a parcel app) like this:import { fetchPeople } from '@lomse/api'
Since
my-app
project is a TypeScript project, the statement above is definitely going to throw the error below:Cannot find module '@lomse/api' or its corresponding type declarations.
Is there a way to fix this?
-
Android 11 image saving issue
The below function was working properly in android 10 but after updating to android 11 it does not work in apache cordova-phonegap
function clickPhoto(source) { navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 20,destinationType: Camera.DestinationType.FILE_URI,saveToPhotoAlbum: true}); };
-
How to create an API for an Android to request data from MySQL
Good day and good week-end
I am a begginer with Smartphone application. I finally success to install Cordova and I created two platform (ios/Android). My goal is to create a small smartphone application to show a map withe localisation of station. The idea is to start building a first page, same as this one (only the map) For the map, I am using leadlet
With cordova, I already could show a map, but now I need to make a request to my MySQL database to collect the geolocalisation of the station.
Someone recommended me to never request from the Smartphone app, but instead , creating an API on my website, and retreive the data from there with a JSON format. And that nice.
But I have no idea, how an API should look like? Is a PHP file which return a JSON format result? But how Cordova will collect and use the received data?
Someone could show me an example of an API? Or is there tutorials
Many thanks and enjoy your week-end
-
AndroidSDK Apk creation vs Ionic Cordova prod build
I am new to Ionic and android app development, and i need your help to clarify my basic questions
I am using ionic capacitor for creating APP, and further using androidSDK for building apk. When i go to ionic website , it says ionic cordova build release to create apks.
Why do i need to use ionic cordova platform for building ? if am i expected to add cordova as integration? iF cordova will go away soon and Capacitor is next , then why we have to use cordova .
-
Ionic angular routerLink directive does not work
An application is built with Ionic Angular. An Angular routing approach(routerLink) does not work. In the documentation, Ionic suggests using ionic-router-outlet and routerLink. There are notations on many pages. What I do, but it does not work. I use the lazy-loading router approach. The application started from a template with tabs that used lazy-loading routers. Tabs work well. But routerLink is silent. RouterModule is imported almost everywhere.
I will be pleased with any tip.
-
how to implement a search bar in ionic
How can i add a search functionality into a angular and ionic project. I tried doing this with the following code below but it doesn't work.
This is the code i tried
filterusers(evt) { const search = evt.srcElement.value; console.log(search); if(!search) { return; } this.employees = this.employees.filter(currentgoal => { if(currentgoal.FName && search) { if(currentgoal.FName.toLowerCase().indexof(search.toLowerCase()) > -1) { return true; } return false; } }); }
how can I do it?