Angular 5+ http发布问题

时间:2018-04-22 03:57:39

标签: angular rest json-server

我能够从驻留在我的localhost上的JSON文件中检索我的对象。但是,在帖子上,我得到了。

Cannot read property 'id' of undefined

在我传入的模拟对象上,如果我添加一个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在我的localhost上允许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 个答案:

答案 0 :(得分:1)

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

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

  2. 您可以在用户输入ID时传递ID。

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

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