微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

类型对象的角度参数不可分配给参数从不

如何解决类型对象的角度参数不可分配给参数从不

我正在学习使用 Angular、Node 和 Express 构建留言板的 Angular 教程。我的后端完全没问题。到目前为止,它运行良好并在端点返回数据。现在在前端,我收到有关消息对象无法分配给参数类型“从不”的错误?什么?

Error: src/app/app.component.ts:17:33 - error TS2345: Argument of type 'object' is not assignable to parameter of type 'never'.
     17     this.messages.messages.push(message);

    

app.component.ts

import { Component,ViewChild } from '@angular/core';
import { MessagesComponent } from './messages.component';
import { NewMessageComponent } from './new-message-componet';

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {
 //Using the ViewChild decorator to push the data from the parent component
  //to the MessagesComponent message array. 
  @ViewChild(MessagesComponent) messages: MessagesComponent;

  onPosted(message:object) {
    //console.log(message);
    this.messages.messages.push(message);
  }
  
}

messages.component.ts

import { Component } from '@angular/core'
import { WebService } from './web.service'

@Component({
  selector: 'messages',template: `
    <div *ngFor="let message of webService.messages">
        <mat-card class="card">
            <mat-card-title>{{message.owner}}</mat-card-title>
            <mat-card-content>{{message.text}}</mat-card-content>
        </mat-card>
    </div>
    `
})
export class MessagesComponent {
  messages: any;
  constructor(private webService: WebService) {
  } 
}

web.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';


@Injectable()
export class WebService {

  BASE_URL = 'http://localhost:1234/api';

  messages = [] as any;

  constructor(private http: HttpClient) {
    this.getMessages();
  }

  async getMessages() {
    var response = await this.http.get(this.BASE_URL + '/messages').toPromise;
    this.messages = JSON.stringify(response);
  
  }

  postMessage(message:object) {
    //return this.http.post(this.BASE_URL + '/messages',message,{ responseType: 'text' }).toPromise();
    return this.http.post(this.BASE_URL + '/messages',message).toPromise();
  }

}

app.component.html

<h1>Message Board</h1>
<mat-slider min="1" max="100" step="1" value="1"></mat-slider>
<new-message (onPosted)="onPosted($event)"></new-message>
<messages></messages>

如果有人知道我需要在这里做什么,我将不胜感激。 谢谢, 钢铁侠

解决方法

在 messages.component.ts 中试试这个:

messages = [];

我认为您应该初始化消息,以便您可以推送它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。