最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I make a function run only when I reload the page with angular? - Stack Overflow

programmeradmin3浏览0评论

What I want to do is shuffle or riffle a number and then stock it in an array, to later use it in the view, but I only want this when I reload the page. The problem is that every time I go to the ponent it generate a new number. This number I am using to shuffle the order of my products in the view, order:

{{number}}. 

IN THE COMPONENT:

public accesoriosJson:any
    private current_value:any

  constructor(private accesoriosService: AccesoriosService){

    this.accesoriosService.getAccesorios().subscribe(respuesta =>{
        this.accesoriosJson = respuesta;

        this.accesoriosJson.map(currentValue =>{
          this.current_value = currentValue;
              this.current_value.random = Math.ceil(Math.random()*10);
        
        })

    })

  }

IN THE VIEW:

    <div class="div" *ngFor='let accesorios of accesoriosJson' style="order:{{accesorios.random}};" routerLink="{{accesorios.name}}">
        <div class="lupa"><i class="fas fa-search"></i></div>
        <img src="{{accesorios.logo}}">
    </div>
    
   </section>

I tried to do something with window.onload, but clearly I do not know how to use angular, and also I do not have so much experience with typescript, if somebody could help me I would really appreciate it! Thank you!

What I want to do is shuffle or riffle a number and then stock it in an array, to later use it in the view, but I only want this when I reload the page. The problem is that every time I go to the ponent it generate a new number. This number I am using to shuffle the order of my products in the view, order:

{{number}}. 

IN THE COMPONENT:

public accesoriosJson:any
    private current_value:any

  constructor(private accesoriosService: AccesoriosService){

    this.accesoriosService.getAccesorios().subscribe(respuesta =>{
        this.accesoriosJson = respuesta;

        this.accesoriosJson.map(currentValue =>{
          this.current_value = currentValue;
              this.current_value.random = Math.ceil(Math.random()*10);
        
        })

    })

  }

IN THE VIEW:

    <div class="div" *ngFor='let accesorios of accesoriosJson' style="order:{{accesorios.random}};" routerLink="{{accesorios.name}}">
        <div class="lupa"><i class="fas fa-search"></i></div>
        <img src="{{accesorios.logo}}">
    </div>
    
   </section>

I tried to do something with window.onload, but clearly I do not know how to use angular, and also I do not have so much experience with typescript, if somebody could help me I would really appreciate it! Thank you!

Share Improve this question edited Aug 21, 2020 at 21:10 R. Richards 25.2k10 gold badges66 silver badges65 bronze badges asked Aug 21, 2020 at 21:08 simon blancosimon blanco 1482 gold badges4 silver badges12 bronze badges 1
  • Do you want your function to be executed only when REloading or when loading and reloading? If the answer is the first one, you can use a token in the session and execute the function in the main scope of your Javascript with the condition that the token has to exist. If the answer is the second one, simply execute your function "manually" in the main scope. (Maybe I did not understand your problem) – Adrien Kaczmarek Commented Aug 21, 2020 at 21:20
Add a ment  | 

3 Answers 3

Reset to default 2

A simple way is to subscribe to the router events and that will get you the page refreshed or not. NavigationStart is used to tell if the page loaded the first time.

import { Component, OnDestroy } from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import { Subscription } from 'rxjs';

export let browserRefresh = false;

@Component({
  selector: 'my-app',
  templateUrl: './app.ponent.html',
  styleUrls: [ './app.ponent.css' ]
})
export class AppComponent implements OnDestroy {
  name = 'Angular 6';
  subscription: Subscription;

  constructor(private router: Router) {
    this.subscription = router.events.subscribe((event) => {
        if (event instanceof NavigationStart) {
          browserRefresh = !router.navigated;
        }
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Working Example: https://stackblitz./edit/angular-r6-detect-browser-refresh

It's a new number, because each time the page is revisited, the ponent is re-created (a new instance of the ponent is created).

What you need is a singleton service. Singleton services are the ones that only have a single instance across the application.

So you can:

  1. Create the service
  2. Move your code to the service
  3. Inject the service into your ponent.

That way, your number will instantiate only once, when the application loads, and each time you revisit the page, you will see the same number.

Documentation on singleton services.

Documentation on how to inject a service.

This is a very broad description, but as you can see from the information in the links provided, the full answer won't fit here.

A solution can be to generate your random number into the root ponent (propably app-ponent if you didn't changed it) in the ngOnInit() function. Please avoid put code in constructor() function.

After your number as been generated, you can pass it to all the ponents you want : by using @Input/@Output if you have a parent/child hierarchy, or by using a service if you want to share it to every ponent wherever you want

发布评论

评论列表(0)

  1. 暂无评论