如何避免重复使用相同的信息angular8

时间:2019-11-05 21:35:46

标签: angular angular8

我正在开发聊天应用程序。我有一个用户列表。当您单击每一个时,将出现一个框,其中包含每个人已发送的消息。为此,我为用户的每次点击创建一个动态组件,该用户的ID由参数发送,并通过服务获得所有消息。我的问题是,如果同一用户被单击两次,该组件将被复制相同的信息。如何避免重复?这个想法是,如果我单击一个正在显示其聊天框的用户,则不要使用该信息创建另一个组件。我需要一些方法来验证这一点。

app.component.ts

import { Component,ViewChild,ViewContainerRef,ComponentFactoryResolver,ComponentRef,OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ConversacionComponent} from "./components/conversacion/conversacion.component";
import {ChatService} from "./services/chat.service";
import {Mensaje} from "./models/mensaje";

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers:[ChatService]
})
export class AppComponent implements OnDestroy {

    @ViewChild('componentsContainer', { read: ViewContainerRef, static: false }) container: ViewContainerRef;
    private subs: Subscription[] = [];

    public id_usuario_destino:number;
    public personas:Array<any>;
    public id_persona:number;
    public mensajes:Mensaje[];

    ngOnDestroy() {
        // unsubscribe from all on destroy
        this.subs.forEach(sub => sub.unsubscribe());

    }

    onClickAdd = (elemento) => {
        this.id_usuario_destino=elemento.id;
        this.id_persona=this.id_usuario_destino;
        this._chatService.getMessages(1,this.id_usuario_destino).subscribe(
            response=>{
                if(response.mensajes){
                    this.mensajes=response.mensajes;

                    const factory = this.componentFactoryResolver.resolveComponentFactory(ConversacionComponent);
                    const component = this.container.createComponent(factory);
                    component.instance.numberCreated = this.container.length;
                    component.instance.men = this.mensajes;
                    // subscribe to component event to know when to delete
                    const selfDeleteSub = component.instance.deleteSelf
                        .pipe(tap(() => component.destroy()))
                        .subscribe();

                    // add subscription to array for clean up
                    this.subs.push(selfDeleteSub);

                }


            },
            error=>{
                console.log(error);
            }
        );


    }

    constructor(private componentFactoryResolver: ComponentFactoryResolver,private  _chatService:ChatService) {
        this.personas=[
            {id:"2",
                nombre:"sergio"
            },
            {id:"3",
                nombre:"jhoyner"
            },
            {id:"4",
                nombre:"gerardo"
            },
            {id:"5",
                nombre:"fabrizio"
            }
        ]
    }



}

app.component.html

<div class="sidenav">
  <ul *ngFor="let persona of personas">
    <li><a id="{{persona.id}}"(click)="onClickAdd($event.target)">{{persona.nombre}}</a></li>
  </ul>

</div>
<ng-template #componentsContainer></ng-template>

conversacion.component.ts

import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import {Mensaje} from "../../models/mensaje";

@Component({
    selector: 'app-conversacion',
    templateUrl: './conversacion.component.html',
    styleUrls: ['./conversacion.component.css']
})
export class ConversacionComponent implements OnInit {
    @Output() deleteSelf: EventEmitter<void> = new EventEmitter<void>();
    @Input() numberCreated: number;
    @Input() men:Mensaje[];

    constructor() { }

    ngOnInit() {
    }

}

conversacion.component.html

<button (click)="deleteSelf.emit()" style="background-color: blue; color: white">close window</button>

<p>Number at time of creation: {{ numberCreated }}</p>
<div *ngFor="let message of men">
    {{message.contenido}}--{{message.fecha}}
</div>
<hr>

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以仅跟踪已添加的ID数组,然后在onClickAdd方法中检查ID是否已在数组中,如果不存在,则不要执行其余方法。像下面这样的东西,带有'alreadyDone'变量:

export class AppComponent implements OnDestroy {

    @ViewChild('componentsContainer', { read: ViewContainerRef, static: false }) container: ViewContainerRef;
    private subs: Subscription[] = [];

    public id_usuario_destino:number;
    public personas:Array<any>;
    public id_persona:number;
    public mensajes:Mensaje[];

    public alreadyDone : number[];

    ngOnDestroy() {
        // unsubscribe from all on destroy
        this.subs.forEach(sub => sub.unsubscribe());

    }

    onClickAdd = (elemento) => {
        if(alreadyDone.findIndex(x => x === elemento.id) === -1)
        {
            alreadyDone.push(elemento.id);
            this.id_usuario_destino=elemento.id;
            this.id_persona=this.id_usuario_destino;
            this._chatService.getMessages(1,this.id_usuario_destino).subscribe(
                response=>{
                    if(response.mensajes){
                        this.mensajes=response.mensajes;

                        const factory = this.componentFactoryResolver.resolveComponentFactory(ConversacionComponent);
                        const component = this.container.createComponent(factory);
                        component.instance.numberCreated = this.container.length;
                        component.instance.men = this.mensajes;
                        // subscribe to component event to know when to delete
                        const selfDeleteSub = component.instance.deleteSelf
                            .pipe(tap(() => component.destroy()))
                            .subscribe();

                        // add subscription to array for clean up
                        this.subs.push(selfDeleteSub);

                    }


                },
                error=>{
                    console.log(error);
                }
            );
        }


    }

    constructor(private componentFactoryResolver: ComponentFactoryResolver,private  _chatService:ChatService) {
        this.personas=[
            {id:"2",
                nombre:"sergio"
            },
            {id:"3",
                nombre:"jhoyner"
            },
            {id:"4",
                nombre:"gerardo"
            },
            {id:"5",
                nombre:"fabrizio"
            }
        ]
    }
}