简体   繁体   English

Angular 5+ http发布问题

[英]Angular 5+ http post issue

I'm able to retrieve my objects just fine from a JSON file that resides on my localhost. 我可以从本地主机上的JSON文件中检索对象。 However, upon post, I get. 但是,发布后,我得到了。

Cannot read property 'id' of undefined

On the mock object I'm passing in, If I add an id property and some random number, it works. 在我传入的模拟对象上,如果添加id属性和一些随机数,则可以正常工作。 But I don't want to have to pass in an id. 但我不想传递ID。

Here's the service: 这是服务:

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

}

Here is where I pass in the mock object: 这是我传递模拟对象的地方:

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

I'm using json-server to allow REST operations on my localhost. 我正在使用json-server允许在本地主机上进行REST操作。

Contents of http://localhost:3000/tiles.json 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"
      }
    }
  ]
}

There are two ways you can solve this issue. 有两种方法可以解决此问题。

  1. If you have access to the back-end code you can change it to ignore the id field form the request accepted. 如果您有权访问后端代码,则可以更改它以忽略接受的请求中的id字段。 Instead to auto increment the id field. 而是自动增加id字段。

  2. You can pass an id without the user entering an id. 您可以传递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.',
       }
   };

I hope that helps. 希望对您有所帮助。 If it does not work plz feel free to comment. 如果不起作用,请随时发表评论。 I am right there. 我就在那里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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