Angular 5+ http post 问题

Angular 5+ http post issue

我能够从驻留在本地主机上的 JSON 文件中很好地检索我的对象。但是,在 post 之后,我得到了。

Cannot read property 'id' of undefined

在我传入的模拟对象上,如果我添加一个 id 属性 和一些随机数,它就可以工作。但我不想传递一个 id。

这是服务:

@Injectable()
export class TileService {

  tiles$ = new Subject<any>();
  details$  = new Subject<any>();
  messages$  = new Subject<any>();

  private tilesUrl = 'http://localhost:3000/tiles';

  private httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  constructor(private http: HttpClient) { }

  getTiles(): Observable<Tile[]> {
    return this.http.get<Tile[]>(this.tilesUrl);
  }

   createTile(t: Tile) {
    return this.http.post<Tile>(this.tilesUrl, t, this.httpOptions).subscribe(
      res => {
        console.log(res);
      },
      (err: HttpErrorResponse) => {
        console.log(err.error);
        console.log(err.name);
        console.log(err.message);
        console.log(err.status);
      }
    );
   }

}

这是我传入模拟对象的地方:

@Component({
  selector: 'app-available-tiles',
  templateUrl: './available-tiles.component.html',
  styleUrls: ['./available-tiles.component.css']
})

export class AvailableTilesComponent implements OnInit {

  title = 'Available Tiles';

  tiles: Tile[];


  mockNewTile = {
    title: 'GO',
    description: 'Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.',
    code: {
        snippetA: 'something here.',
        }
  };

  constructor(private tileService: TileService) { }

  ngOnInit() {
    this.tileService.getTiles().subscribe(x => this.tiles = x);
  }

  addTile(t: Tile) {
    this.tileService.tileStream(t);
    this.tileService.messageStream( t.title +  ' tile added.');
  }

  createTile() {
    this.tileService.createTile(this.mockNewTile);
  }
}

我正在使用 json-server 来允许在我的本地主机上进行 REST 操作。

http://localhost:3000/tiles.json

的内容
{
  "tiles": [
    {
      "title": Language A",
      "description": "Language A description.",
      "code": {
        "snippetA": "lang snippet a1",
        "snippetB": "lang snippet a2",
        "snippetC": "lang snippet a3"
      }
    },
       {
      "title": Language B",
      "description": "Language B description.",
      "code": {
        "snippetA": "lang snippet b1",
        "snippetB": "lang snippet b2",
        "snippetC": "lang snippet b3"
      }
    }
  ]
}

有两种方法可以解决这个问题。

  1. 如果您有权访问后端代码,您可以将其更改为忽略已接受请求的 id 字段。而不是自动递增 id 字段。

  2. 您可以在用户不输入 ID 的情况下传递 ID。


npm install uuid --save

import { v4 as uuid } from 'uuid';

 mockNewTile = {
      id : uuid(),
      title: 'GO',
      description: 'Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.',
      code: {
          snippetA: 'something here.',
       }
   };

希望对您有所帮助。如果它不起作用,请随时发表评论。我就在那里