IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

TypeScript Discussion :

Comment utiliser une fonction dans tous les composants


Sujet :

TypeScript

  1. #1
    Membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Juin 2017
    Messages
    77
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2017
    Messages : 77
    Points : 42
    Points
    42
    Par défaut Comment utiliser une fonction dans tous les composants
    Bonjour, mon problème est simple : j'ai une fonction 'addChatWindow(id?: string, thread?: Thread)' instanciée dans mon composant 'ChatWindowsComponent'.
    Je voudrais utilisé cette fonction dans une autre classe 'ChatThreadsComponent'.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
     
    export class ChatWindowsComponent implements OnInit {
     
        windows: Box[] = [new Box()];
     
        constructor() {
            this.windows = [
                new Box()
                ];
        }
     
        ngOnInit(): void {    }
     
        addChatWindow(id?: string, thread?: Thread): void {
            this.windows.push(new Box());
        }
    }

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    export class ChatThreadsComponent implements OnInit {
     
        onCreateChatWindow(id?: string): void {
          addChatWindow(this.thread.id, this.thread);        ?????????????
    }
    Merci d'avance

  2. #2
    Membre habitué
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juillet 2017
    Messages
    81
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Juillet 2017
    Messages : 81
    Points : 132
    Points
    132
    Par défaut
    Bonjour,

    Dans ton exemple, et pour utiliser une fonction que tu vas réutiliser plusieurs fois dans ton application. Je te conseille de rattacher cette fonction à un service. Tu instancies ton service dans tes composants et tu utilises cette fonction.

    Ps: tu peux aussi rattacher des fonctions à des models mais ce n'est pas adapté à ton cas selon moi

  3. #3
    Membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Juin 2017
    Messages
    77
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2017
    Messages : 77
    Points : 42
    Points
    42
    Par défaut
    Merci de ta réponse
    Voici ce que j'ai fait. Est ce bien comme cela qu'il faut faire pour instancier un service, car cela ne fonctionne pas et je ne comprends pas pourquoi ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
     
    import { Injectable } from '@angular/core';
    import { Subject, BehaviorSubject, Observable } from 'rxjs';
    import { Box } from './box.model';
     
    @Injectable()
    export class BoxService {
     
        windows: Box[];
     
        constructor() {    }
     
        addBox(box: Box): void {
            this.windows.push(new Box());
        }
    }
     
    export const boxsServiceInjectables: Array<any> = [
        BoxService
    ];
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    import { uuid } from '../util/uuid';
     
    export class Box {
        id: string;
        thread: Thread;
     
        constructor(id?: string,
                    thread?: Thread) {
            this.id = id || uuid();
            this.thread = thread || null;
        }
    }
    Faut-il initialiser windows dans le constructeur de mon service et non plus dans mon composant 'Chat-windows' ?

    Merci de votre aide ...

  4. #4
    Membre habitué
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juillet 2017
    Messages
    81
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Juillet 2017
    Messages : 81
    Points : 132
    Points
    132
    Par défaut
    Quelle erreur as-tu quand tu appelles ton service?

    Je pense que tu dois déclarer ton window dans le composant.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @Injectable()
    export class BoxService {
     
     
     
        constructor() {    }
     
        addBox(windows: Box[], box: Box): Box[]{
            windows.push(new Box());
            return windows as Box[];
     
        }
    }

  5. #5
    Membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Juin 2017
    Messages
    77
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2017
    Messages : 77
    Points : 42
    Points
    42
    Par défaut
    Merci pour ton aide !! C'est bon cela fonctionne même en laissant la variable windows initialisé dans le service. Il fallait que j'initialise ensuite windows dans mon composant comme ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    export class ChatWindowsComponent implements OnInit {
        windows: Box[];
     
        constructor(public boxService: BoxService) {
        }
     
        ngOnInit(): void {
            this.windows = this.boxService.windows;
        }
    }
    J'ai juste un problème mais je ne sais pas trop d'où cela vient. Lorsque je crée une fenêtre de discussion avec addChatWindow, les fenêtres déjà ouvertes changent elles aussi de destinataire. Il m'est impossible d'avoir 2 fenêtres avec 2 destinataires différents d'ouvertes.
    Est ce dût à l'initialisation le service ?

    Voici mes codes pour plus d'explication :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
     
    export class ChatThreadComponent implements OnInit{
      @Input() thread: Thread;
      selected = false;
      currentThread: Thread;
      currentBox: Box;
     
      constructor(public threadsService: ThreadsService,
                  public boxService: BoxService) {
      }
     
      ngOnInit(): void {
        this.threadsService.currentThread
            .subscribe((currentThread: Thread) => {
              this.selected = currentThread &&
                  this.thread &&
                  (currentThread.id === this.thread.id);
            });
      }
     
      clicked(id?: string, thread?: Thread): void {
        this.boxService.addChatWindow(id, thread);
        this.threadsService.setCurrentThread(thread);
      }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    @Injectable()
    export class ThreadsService {
      constructor(public messagesService: MessagesService) {
              }
     
      setCurrentThread(newThread?: Thread): void {
        this.currentThread.next(newThread);
      }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    <div class="chat-window-container">
        <div *ngFor="let box of windows; let i=index;">
            <chat-window *ngIf = "i<3">
            </chat-window>
        </div>
    </div>

Discussions similaires

  1. [1.x] comment utiliser une fonction dans symfony et backend
    Par safa-ingenieur2010 dans le forum Symfony
    Réponses: 1
    Dernier message: 31/05/2010, 14h12
  2. [Toutes versions] Portée des fonctions : comment créer une fonction commune à tous les classeurs ?
    Par akr54 dans le forum Macros et VBA Excel
    Réponses: 2
    Dernier message: 09/02/2010, 11h29
  3. Comment utiliser une fonction dans une fonction
    Par hatenaku dans le forum Langage
    Réponses: 3
    Dernier message: 19/04/2008, 20h00
  4. Comment utiliser une fonction dans une classe.
    Par metalamania dans le forum wxPython
    Réponses: 5
    Dernier message: 17/02/2008, 17h50
  5. COmment faire une recherche dans tous les dossiers
    Par Djohn dans le forum Outlook
    Réponses: 2
    Dernier message: 28/06/2007, 19h27

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo