简体   繁体   中英

Pass id from component to service.ts Angular

im working in chat project angular with websocket, let me show you the architecture of my project, so i create a module named chatting contains the list of users whene i select one of them another component opened, this component named message.

i want to send the id with the message to the backend by service, the id obtained from URL with router.params['id'] in the message.ts.

how can i transfer this id to the service.ts?

PS i have do a trial with the methods of the websocket but doesn't work

------ My Trial ------

message.component.ts

this.idUser = this.route.snapshot.params['id'];
sendMessage(event: any, avatar: string,idUser:Number) {
    let obj: Message = {
      text: event.message,
      avatar: avatar,
      username: this.username,
      idUser: this.idUser
    } ;
console.log("id sedmessage:",obj.idUser)
    this.chatService.sendMessage(obj);
  }

service.ts

idUser:Number=0;
initializeWebSocketConnection() {
   
    const serverUrl = 'http://localhost:8020/chat-websocket/'+this.idUser ;
    console.log("id service :",serverUrl)
    const ws = new SockJS(serverUrl);
    this.stompClient = Stomp.over(ws);
    const that = this;

    this.stompClient.connect({}, function(frame:any) {
      let message:any;
      that.stompClient.subscribe('/chat/messages', function (message:any) {
        if (message.body) {
          const obj = JSON.parse(message.body);
          that.addMessage(obj.text, obj.username, obj.avatar,obj.idUser);
        }
      });
    });
  }

  addMessage(message: any, username: string, avatar: string,idUser:Number) {
    this.messages.push({
      text: message,
      date: new Date(),
      user: {
        name: username,
        avatar:avatar,
        idUser:idUser
      }
    });
  }

  // Send a chat message using stomp client
  sendMessage(msg: Message) {
    this.stompClient.send('/app/sendmsg', {}, JSON.stringify(msg));
  }}

interface IMessage {

  text: string;
  date: Date;
  user: IUser;
}

interface IUser {
  idUser:Number;
  name: string;
  avatar: string;
}

It depends how you set it up, are you using service directly or store (ie.: https://ngrx.io or https://rxjs.dev ).
If you use the websocket service directly you need to inject it on constructor and call the method on your message component init, maybe have a listener on the router for changes.
In case you use store you can create a Subject ( https://rxjs.dev/guide/subject ) in your websocket and subscribe to it in a reactive way so every new data is send to backend.

Edit note: I included the user id is passed within the message, if is a different id (ie.: chat id) and you need it for initiate a connection, then you have to change your service to have a setup method that you can pass the id so it closes and reopen with new id.


interface Message {
  text: string;
  date: Date;
  user: User;
}

interface User {
  id: number;
  name: string;
  avatar: string;
}

export class MessageComponent implements OnInit {
  userId = 0;
  username = '';

  constructor(
    private route: ActivatedRoute,
    private service: Service
  ) {
  }

  ngOnInit(): void {
    this.userId = this.route.snapshot.params.id;
  }

  sendMessage(event: any, message: string, avatar: string): void {
    console.log('id send message:', this.userId);

    this.service.sendMessage({
      text: message,
      date: new Date(),
      user: {
        id: this.userId, // refactor in your backend userId or just id
        name: this.username,
        avatar,
      }
    });
  }
}



@Injectable({
  providedIn: 'root'
})
export class Service {
  readonly SERVER_URL = 'http://localhost:8020/chat-websocket/'; // fixme: use window.
  sender: Subject<Message> = new Subject<Message>();
  messages: Message[] = [];

  stompClient: any;

  constructor() {
    this.initializeWebSocketConnection();
  }

  initializeWebSocketConnection(): void {
    // I don't know what initial setup you required just using your code
    this.stompClient = Stomp.over(new SockJS(serverUrl));

    this.stompClient.connect({}, (frame: any) => {

      // subscriber for new messages you want to send, user id is passed here.
      this.sender.subscribe(
        next => this.stompClient.send(next.user.id + '/app/sendmsg', {}, JSON.stringify(next))
      );

      this.stompClient.subscribe('/chat/messages', (message: any) => {
        // fixme: you probably could use a mapper here
        if (message.body) {
          const obj = JSON.parse(message.body);
          this.addMessage(obj.text, obj.username, obj.avatar, obj.idUser);
        }
      });
    });
  }

  addMessage(message: any, username: string, avatar: string, userId: number): void {
    this.messages.push({
      text: message,
      date: new Date(), // fixme: backend should set timestamps
      user: {
        id: userId,
        name: username,
        avatar
      }
    });
  }

  // Send a chat message using stomp client
  sendMessage(message: Message): void {
    this.sender.next(message);
  }
}


Routing with params please find here for more https://angular.io/guide/router#link-parameters-array

Configure:

{ path: 'yourURL/:id', component: YourComponent }

Active:

<a [routerLink]="['yourURL', yourId]"></a>

ResultingURL:

http://localhost:4200/yourURL/1

Read:

this.route.snapshot.snapshot.get('id');

navigation.component.ts

Here is the code to navigated with parmas

this.route.navigate(['yourURL, this.yourId]);

If it's in template you have to follow below code

<a [routerLink]="['yourURL', yourId]"></a>

message.component.ts

In message component you have to get params id

constructor(private route: ActivatedRoute,private chatService:ChatService) {}

  ngOnInit(): void {
    this.route.paramMap.pipe(
    switchMap(params => {
    this.idUser = Number(params.get('id'));
   })
  );
}
   

Then you have to pass service.ts this.idUser

 this.chatService.sendMessage(this.idUser);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM