Angular component not destroying after moving to another component
I have an angular component which is implementing OnDestroy
method.
export class MyComponent implements OnInit, OnDestroy {
constructor(private elementRef: ElementRef,
....
ngOnInit() {
this.selection.clear();
this.formGrid();
}
ngOnDestroy(): void {
this.elementRef.nativeElement.remove();
}
}
However, when I move to another component even then I see that MyComponent
is not destroying.
I can see that apis used within MyComponent
are still running.
Debugging Details:
When I move to another component MyComponent2
I see that OnDestroy
from MyComponent
is getting called.
However, if check the Network tab
under developer tools I see that even after the execution of OnDestroy
, all apis under MyComponent
are still running.
Please also note that MyComponent
is only using promise for the services and I am not subscribing to any services.
See also questions close to this topic
-
Creating a linked list object using js
I want to make a linked list using
custom Object
that pushes a value, pop a value, display all its content, remove an item from a specific place, and insert at a specific place as long as the value is missing from the sequence otherwise through an exception. All of the properties should be defined using data descriptor, prevent them from being deleted, iterated, or being modified.I can do no more than this ... I'm new to js.
var linkedList = {}; /* linkedList.name = 'Ahmed'; [].push.call(linkedList, 'sad', "sd"); */ Object.defineProperty(linkedList, "name", { value: "mohamed", writable: false, configurable: false, enumerable: false }) linkedList.next = {'sd':'as'};
Any help? thanks in advance
-
Trying to trigger a CSS animation with a button press through Javascript
I'm trying to trigger a CSS animation with a button press by using Javascript. I've used other question and answers here, but to no avail. My code seems like it should work -- what am I missing? When I click the button, the background color of the div which I specify should change color over 2 seconds to light blue. I've tried changing the color of both my Body and my Test div, but nothing changes. My alert() triggers, which is confusing as it is in the same function as my colorChange.
<!DOCTYPE html> <html lang="en"> <head> <title><model-viewer> example</title> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script> function colorChange() { alert("The button works"); document.getElementByID('test').style.animation="changeColor"; } </script> <style> body { background-color: darkblue; -webkit-transition: all 2s ease; -moz-transition: all 2s ease; -o-transition: all 2s ease; -ms-transition: all 2s ease; transition: all 2s ease; } .test { width: 500px; height: 500px; background-color: pink; } @keyframes changeColor { to { background-color: lightblue; } } </style> </head> <body id="body"> <div class="test"></div> <button id="button" onclick="colorChange()">test animation</button> </body> </html>
-
No output from (GET) Ajax Result From Php Array with json_encode
I have a GET form that gets a Php Array and json encodes it. The Issue I am having is the succes data is not displaying. I want the success to display data in a Alert or console but for some reason its not working. I have tried many options. Thanks for your help.
PS:I know the GET and all files work because when I got the script the Ajax reponse result would populate/append a Table sucessfully. I am modifing it.
Here is the php index file with the AJAX:
<!doctype html> <html> <head> <title>Return JSON response from AJAX using jQuery and PHP</title> <link href="style.css" type="text/css" rel="stylesheet"> <script src="jquery-3.1.1.min.js" type="text/javascript"></script> </head> <body> <script> $(document).ready(function(){ $.ajax({ url: 'ajaxfile.php', type: 'get', dataType: 'JSON', success: function(data){ var obj = jQuery.parseJSON(data); alert(obj.username); } }); }); </script> </body> </html>
Here is the php file that quries the database and encodes/array json:
<?php $return_arr = array(); $sql = "SELECT * FROM users ORDER BY NAME"; $result = $conn->query($sql); //Check database connection first if ($conn->query($sql) === FALSE) { echo 'database connection failed'; die(); } else { while($row = $result->fetch_array()) { $id = $row['id']; $username = $row['username']; $name = $row['name']; $email = $row['email']; $return_arr[] = array("id" => $id, "username" => $username, "name" => $name, "email" => $email); } // Encoding array in JSON format echo json_encode($return_arr); } ?>
echo json_encode array output from the php file looks like below (test content):
[{"id":"1","username":"jiten","name":"Jiten singh\t","email":"jiten9"},{"id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldee"},{"id":"3","username":"mayank","name":"Mayank","email":"mayank"},{"id":"9","username":"mohit","name":"Mohit","email":"mohit"},{"id":"13","username":"mukesh","name":"Mukesh","email":"mukesh"},{"id":"6","username":"nitin","name":"Nitin","email":"niti"},{"id":"12","username":"palash","name":"Palash","email":"palash"},{"id":"7","username":"rahul","name":"Rahul singh","email":"rahul"},{"id":"10","username":"rohit","name":"Rohit singh","email":"rohit"},{"id":"8","username":"shreya","name":"Shreya","email":"shreyam"},{"id":"11","username":"sonarika","name":"Sonarika","email":"sonarika"},{"id":"5","username":"vijay","name":"Vijay","email":"vijayec"},{"id":"14","username":"vishal","name":"Vishal Sahu\t","email":"visha"},{"id":"4","username":"yssyogesh","name":"Yogesh singh","email":"yoges"}]
when I make the success result (data) and alert(data), this is what I get,empty objects
-
Creating two value range slider from Angular material native component
I need a two value range slider for my app, however none of the packages that I've looked at on NPM etc are 100% suitable for what I need. The Angular Material slider is the most suitable, however it doesn't allow for two values to be used on a single slider.
To get around this, I've had an idea of placing one slider on top of the other, to give the impression of one slider with two values. This works well, and has a smooth behaviour which is one of the requirements that I wanted my slider to have.
However, I would also like to add a bar in between the two slider thumbs, so that the selected range is highlighted and visible. The native slider does have this, but since it only allows one value the highlight starts from 0 and extends to the value of the slider.
Instead I want to have the highlight between the upper and lower values of the thumbs on the slider. But I have no idea how to add this to it. So I was wondering if someone could help me out. I'm not entirely sure if I'd need to add a new element on top of the bar that adjusts to the size between the two thumbs or if I'd have to do something different.
Alternatively if anyone knows how to make NGX-slider allow a smooth step like the angular material slider that would be the best solution and I'd love to hear it. https://www.npmjs.com/package/@angular-slider/ngx-slider
https://angular-9-material-starter-5ueh7p.stackblitz.io
Code so far
<mat-slider class="slider-left"></mat-slider> <mat-slider class="slider-right"></mat-slider> .slider-right { position: relative; left: -128px; } ::ng-deep .mat-slider-track-fill { background-color: rgba(0, 0, 0, 0.26) !important; } ::ng-deep .mat-slider-track-background { background-color: rgba(0, 0, 0, 0.26); }
-
Angular 10 form action not getting variable
I am creating a form in angular, used from a 3rd party, which needs to redirect away from my site for a payment and back.
I have added their sample code (the form which does a post) into my angular app and added a formGroup, and an action to the form (the action is the url I want to redirect to).
<form [formGroup]="tdsvt" (ngSubmit)="onSubmit2021" method="post" id="redirectForm" action="{{redirectUrl}}"> <input type="hidden" name="id" formControlName="reqID" /> </form>
I have changed the action to the variable that is needed, but it does not redirect and it stays blank. I have tried doing a normal post request and subscribe like so:
return this.http.post<any>(redirectUrl, data);
But I am hit with a CORS issue as it is a total different URL.
How can I get the action to work as a variable and redirect? Or if I shouldn't use an action, what's the best method around this?
Thank you
-
Child route with fragment
I have a page with a side menu, each side menu item has a routerLink that sends a different fragment. I want to know if it is possible that this new route with the fragment has a child route.
Example:
Side menu:
<button type="button" routerLink="['/pageA']" fragment="frag">btn side menu</button>
On click this button, the route would look like this: http://localhost:4200/#/pageA#frag
Content Page
<button type="button" routerLink="['child-a']">A</button> <button type="button" routerLink="['child-b']">B</button> <router-outlet></router-outlet> // Here son A or son B will be loaded
And when click on button A, the route would look like this: http://localhost:4200/#/pageA#frag/child-a
page-routing.module.ts
const routes: Routes = [ { path: '', component: PageAComponent, children: [ { path: 'child-a', component: ChildAComponent, }, { path: 'child-b', component: ChildBComponent, }, ], }, ];
-
How can I display a select list within an Angular Material table?
How can I display a select list within an Angular Material table?
error:
TS2339: Property 'element' does not exist on type 'MyaccountComponent'. <mat-option *ngFor="let role of element.validRoles" [value]="role.value">
I get the same error if I change
element.validRoles
tovalidRoles
too.Component:
export class MyaccountComponent implements OnInit { displayedColumns: string[] = ['email', 'role', 'rolestatus', 'validRoles']; dataSource = []; ngOnInit(){ this.getAllUsers(); } constructor(private userService: UserService) { } getAllUsers(){ const obs = this.userService.getAllRegisteredUsers(); obs.subscribe(data => { console.log(data.users); this.dataSource = data.users }); } }
Template:
<ng-container matColumnDef="validRoles"> <th mat-header-cell *matHeaderCellDef> Assign Role</th> <mat-form-field appearance="fill"> <mat-label>Roles</mat-label> <mat-select> <mat-option *ngFor="let role of element.validRoles" [value]="role.value"> {{role.viewvalue}} </mat-option> </mat-select> </mat-form-field> </ng-container>
My data is in the format:
data.users.validRoles = [ {value: "admin", viewvalue: "Admin"} ];
-
Trigger AngularComponent-constructor on startup with PreLoadingStrategy
The goal: trigger a component residing in a module, so my subscription in the ctor of the component is activated. I'm using PreloadAllModules as a preloadingStrategy. But it's not happening.
I need to subscribe to some events in de constructor of my FriendsComponent. the setup is like this:
FriendsComponent is shown in the template of the SocialComponent, which is part of the SocialModule.
social.component.html
<div> <friends-component></friends-component> </div>
the SharedModule declares the FriendsComponent. AppModule imports SharedModule, RouterModule for AppModule is like this:
{ path: 'social', component: SocialModule, children: [ { path: 'friends', component: FriendsComponent } ] },
I think the problem is because the FriendsComponent is not part of a router-outlet? Can it be done without a router-outlet?
If a module would be pre- or eager loaded, would it automatically trigger the constructors (and the subscription)? Is the issue with my preloading strategy?
I have tried adding: data:{preload:true} to the paths declared in routermodule.
Everything works fine, when the user activates the SocialModule (for instance by clicking on a button with a routerLink to social/friends), but I want it activated on startup (just not shown on any html) I'm working with Angular Ivy, but think I'm still missing the points. Any help is appreciated
-
Issues with JS resourcses i springboot and angularJS application
Have a Springboot application with AngularJS. Have all .js controllers and services.
I have an index.ftl file which use ui-routers on index.ftl to display buttons and have links to all .js files (angular controllers and service files which needs to be loaded at initializations of all ui-routers).
I have spring security for http links but issue is anyone can access my js files using link like this: http://localhost:8080/js/lib/abc.js
I can not make them bound using http security because in that case even my homepage will not load. what can i do here, don't want to expose all my angular controllers and services files.
-
where Router.events should be used in angular
I want to know the current route of the application, when i checked i got solution where router.events.subscribe is used. But i saw conflicting solution like, some were coding in constructor and some were coding in ngOninit. Where exactly the code router.events.subscribe has to be placed.
-
Angular routing same path different guard
I want to use the same path
ticket
because I want to redirect when save something (Use same component to Update Ticket ). But there is a problem withcanActivate
. What is the best way to fix it?const router: Routes = [ { path: '', component: HomeLayoutComponent, canActivate: [AuthGuard], children: [ { path: '', component: HomeComponent }, { path: 'ticket', canActivate: [SupportGuard], component: TicketComponent }, { path: 'ticket', canActivate: [CustomerGuard], component: SiteTicketComponent }, .... ] }, { path: '', component: LoginLayoutComponent, children: [ { path: 'login', component: LoginComponent }, { path: 'signup', component: SignupComponent }, ] }, { path: '**', component: Error404Component } ]
Thanks in advance.
-
How to save value of counter when onDestroy callback is called?
I'm working on a small and simple android app where I increase or decrease a counter on button click. When the app goes
onStop
, I'm saving the current counter value in the text file and when I come back to the app, I'm reading the written value and showing it on screen in theTextView
. The problem is that when I come back to the app and receive the value and try to increment it, it starts to count from 0. However, the problem happens if I leave the app andonDestroy
callback is called, but if I rotate the phone and the sameonDestroy
are called the counter works as it is expected to work. My question is how to continue increasing the counter from the latest saved value?Here is my code:
MainActivity
public class MainActivity extends AppCompatActivity { private static final String FILE_NAME = "test.txt"; TextView textView; private int count; private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text1); readTextFile(); if (savedInstanceState != null){ count = savedInstanceState.getInt("count"); textView.setText(String.valueOf(count)); } } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("count", count); } public void decrement(View view) { count --; textView.setText(String.valueOf(count)); } public void increment(View view) { count++; textView.setText(String.valueOf(count)); } @Override protected void onStop() { super.onStop(); String text = String.valueOf(count); FileOutputStream fos = null; try { fos = openFileOutput(FILE_NAME, MODE_PRIVATE); try { fos.write(text.getBytes()); Toast.makeText(this, "Saved to " + getFilesDir() + FILE_NAME, Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } count = Integer.parseInt(text); Log.i(TAG,"onStop"); } @Override protected void onPause() { super.onPause(); Log.i(TAG,"onPause"); } @Override protected void onDestroy() { super.onDestroy(); Log.i(TAG,"onDestroy"); } public void readTextFile(){ FileInputStream fis = null; try { fis = openFileInput(FILE_NAME); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String text; while ((text = br.readLine()) != null){ sb.append(text); } textView.setText(sb.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
layout:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:screenOrientation="sensorLandscape" tools:context=".MainActivity"> <TextView android:id="@+id/text1" android:layout_width="167dp" android:layout_height="45dp" android:gravity="center" android:text="0" android:textColor="#0C0C0C" android:textSize="36sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.603" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="decrement" android:text="-" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/text1" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="increment" android:text="+" app:layout_constraintBottom_toTopOf="@+id/text1" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
-
Reinitialising Fragment when closing activity
I have an Activity with a fragment, this fragment has a map in it and some markers. I run a service in the background that changes the position of the markers.
Each Marker has a boolean "isDrawn" and whenever the boolean is set to false the map is updated by adding drawing the marker ( I use LiveData to observe the markers) Whenever I close the Activity that contains the fragment I call onDestroyView, which sets isDrawn of every marker to false. That way when I open the Activity again, the markers get drawn one more time. All of this works fine.
The problem is this: in the Fragment I can tap on the markers, which opens a view that has a button which opens another Activity, when I close this Activity (With BackButton) and if a marker changed its position (through the service) when I was in said Activity, I find that there are two of the same marker on the map.
Any idea what I could do? Should I remove the fragment and create it again when I close the activity? is that possible? if so how should I proceed?
-
unable to destroy activity Android
here is my java code
@Override protected void onDestroy() { int i; super.onDestroy(); if (bitmapList != null) { for (i = INDEX_COLLAGE; i < bitmapList.length; i += INDEX_COLLAGE_BACKGROUND) { if (bitmapList[i] != null) { bitmapList[i].recycle(); } } } if (collageView != null) { if (collageView.shapeLayoutList != null) { for (i = INDEX_COLLAGE; i < collageView.shapeLayoutList.size(); i += INDEX_COLLAGE_BACKGROUND) { for (int j = INDEX_COLLAGE; j < collageView.shapeLayoutList.get(i).shapeArr.length; j += INDEX_COLLAGE_BACKGROUND) { if (collageView.shapeLayoutList.get(i).shapeArr[j] != null) { collageView.shapeLayoutList.get(i).shapeArr[j].freeBitmaps(); } } } } if (collageView.maskBitmapArray != null) { for (i = INDEX_COLLAGE; i < collageView.maskBitmapArray.length; i += INDEX_COLLAGE_BACKGROUND) { if (collageView.maskBitmapArray[i] != null) { if (!collageView.maskBitmapArray[i].isRecycled()) { collageView.maskBitmapArray[i].recycle(); } collageView.maskBitmapArray[i] = null; } } } } if (adWhirlLayout != null) { adWhirlLayout.removeAllViews(); adWhirlLayout.destroy(); } } private void backButtonAlertBuilder() { AlertDialog.Builder builder = new AlertDialog.Builder(CreateCollageActivity.this); builder.setMessage("Would you like to save image ?").setCancelable(true).setPositiveButton("Yes", new OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (analytics != null) analytics.logEvent(Analytics.Param.IMAGE_SAVE, ""); new SaveImageTask().execute(); } }).setNeutralButton("No", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } });
The app crashes when i click back button..when i debugged the code it showed java.lang.RuntimeException: Unable to destroy activity and HVDactivities.CreateCollageActivity.onDestroy(CreateCollageActivity.java:740)