将 id 从组件传递给 service.ts Angular

时间:2021-06-05 16:19:03

标签: angular typescript

我正在使用 websocket 进行 angular 聊天项目, 让我向您展示我的项目的架构,因此我创建了一个名为 chatting 的模块,其中包含用户列表,当我选择其中一个打开的另一个组件时,该组件名为 message。

我想通过 service 将带有消息的 id 发送到后端,从 message.ts 中带有 router.params['id'] 的 URL 获取的 id。

如何将此 ID 转移到 service.ts ?

附注 我已经试用了 websocket 的方法,但不起作用

------我的试炼------

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;
}

2 个答案:

答案 0 :(得分:0)

这取决于您如何设置,您是直接使用服务还是商店(即:https://ngrx.iohttps://rxjs.dev)。
如果您直接使用 websocket 服务,则需要将其注入构造函数并调用消息组件 init 上的方法,可能在路由器上有一个监听器以进行更改。
如果您使用 store,您可以在您的 websocket 中创建一个主题 (https://rxjs.dev/guide/subject) 并以反应方式订阅它,以便将每个新数据发送到后端。

编辑注意:我在消息中包含了用户ID,如果是不同的ID(即:聊天ID)并且您需要它来启动连接,那么您必须更改您的服务以获得设置方法您可以传递 id 以便它关闭并使用新 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);
  }
}


答案 1 :(得分:0)

使用参数进行路由,请在此处找到更多信息 https://angular.io/guide/router#link-parameters-array

配置:

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

活跃:

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

结果网址:

http://localhost:4200/yourURL/1

阅读:

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

navigation.component.ts

这是使用 parmas 导航的代码

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

如果它在模板中,您必须遵循以下代码

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

message.component.ts

在消息组件中,您必须获取 params id

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

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

那么你必须通过 service.ts this.idUser

 this.chatService.sendMessage(this.idUser);
相关问题