0

我可以从我的本地主机上的 JSON 文件中很好地检索我的对象。但是,在发布后,我明白了。

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"
      }
    }
  ]
}
4

1 回答 1

0

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

  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.',
       }
   };

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

于 2018-04-22T04:53:57.733 回答