簡體   English   中英

Angular 將對象推送到數組返回不是 function

[英]Angular push objects to array return not function

我正在嘗試將返回的數據從socket.io推送到我的消息數組中,但它說:

錯誤類型錯誤:this.messages.push 不是 function

代碼

messages: any[] = [];

constructor(...){...}

ngOnInit() {
 this.socket.fromEvent('message').subscribe((message: any) => {
   console.log('from socket', message.msg.message); // sample data provided in down
   this.messages.push(message.msg.message);
 });
}

sample data

from socket 
    {id: 51, group_id: 1, user_id: 1, note: "wrwgwwg", deleted_at: null, …}
        created_at: "2020-05-18T08:19:59.000000Z"
        deleted_at: null
        group_id: 1
        id: 51
        note: "wrwgwwg"
        updated_at: "2020-05-18T08:19:59.000000Z"
        user: {id: 1, name: "Sam", username: "admin", phone: "081200000001", photo: null, …}
        user_id: 1
        __proto__: Object

任何的想法?

更新

根據要求我的完整組件代碼。

import { Component, OnInit } from '@angular/core';
import { Plugins } from '@capacitor/core';
import { MenuController, LoadingController } from '@ionic/angular';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { AlertService } from 'src/app/Services/alert.service';
import { SendChatService } from 'src/app/Services/send-chat.service';
import { ActivatedRoute } from '@angular/router';
import { GroupsService } from 'src/app/Services/groups.service';
import { AuthService } from 'src/app/Services/auth.service';
import { User } from 'src/app/Services/user.service';
const { Toast } = Plugins;

// socket.io
import { Socket } from 'ngx-socket-io';


@Component({
  selector: 'app-chat',
  templateUrl: './chat.page.html',
  styleUrls: ['./chat.page.scss'],
})
export class ChatPage implements OnInit {

  newSegment: string;
  public chat: FormGroup;
  messages: any[] = [];
  loading: any;
  public user: User;

  constructor(
    private sendChatService: SendChatService,
    private groupsService: GroupsService,
    private menu: MenuController,
    private alertService: AlertService,
    public formBuilder: FormBuilder,
    public loadingController: LoadingController,
    private activatedRoute: ActivatedRoute,
    private authService: AuthService,
    private socket: Socket,
  ) {
    this.menu.enable(true);
    const id = this.activatedRoute.snapshot.paramMap.get('id');
    this.chat = this.formBuilder.group({
      newMessage: ['', Validators.required],
      group_id: id
    });
  }

  async ionViewDidEnter() {
    (await this.authService.user()).subscribe(
      user => {
        this.user = user;
      }
    );
  }

  ionViewWillLeave() {
    this.socket.disconnect();
  }

  ngOnInit() {
    Toast.show({
      text: 'Selamat Datang Ke grup chat.'
    });
    this.getData();

    // socket.io
    this.socket.connect();

    // get back stored data form "sendMessage" and add it to the list
    this.socket.fromEvent('message').subscribe((message: any) => {
      console.log('from socket', message.msg.message);
      this.messages.push(message.msg.message);
    });
    // end of socket.io
  }

  async getData() {
    this.loading = await this.loadingController.create({
      message: 'Please wait...',
      spinner: 'crescent',
      duration: 2000
    });

    await this.loading.present();

    const id = this.activatedRoute.snapshot.paramMap.get('id');
    this.groupsService.getGroupsDetails(id).subscribe(res => {
      this.messages = res.data;
      this.hideLoading();
    });
  }

  private hideLoading() {
    this.loading.dismiss();
  }

  doRefresh(event) {
    console.log('Begin async operation');
    setTimeout(() => {
      console.log('Async operation has ended');
      event.target.complete();
    }, 2000);
  }

  ionViewWillEnter() {
    this.newSegment = 'chats';
  }

  sendMessage() {
    const chatt = this.chat.value;
    this.sendChatService.messagesend(chatt.newMessage, chatt.group_id).subscribe(
      (data: any) => {
        this.alertService.presentToast(data.message);
        console.log(data);
        // this.messages.push(data);
        // chatt.newMessage.reset();
        // socket.io (send returned data to socket server - get it back in "ngOnInit")
        this.socket.emit('send-message', { message: data.data });
      },
      error => {
        this.alertService.presentToast(error.statusText);
        console.log(error);
      },
      () => {
        //
      }
    );
  }
}

Messages 開頭是一個數組,但后來我看到了這一行:

this.messages = res.data;

確保 res.data 確實是一個數組。 或者這樣做:

this.messages = [...res.data];

要么:

this.messages.push(res.data);

或修復后端:this.socket.fromEvent('message')...

解決了

我的消息在 ( ref ) 中有notes數組,我需要做的就是在該注釋數組中指向新消息而不是消息本身。

所以最后的代碼是:

this.messages.notes.push(message.msg.message);

代替

this.messages.push(message.msg.message);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM