【发布时间】:2017-03-30 22:23:54
【问题描述】:
我还是新手,但我正在尝试将自己的数据发布到https://jsonplaceholder.typicode.com/users 以供学习。在页面底部,它说要使用npm install -g json-server,所以我在我的项目中运行了该命令,我尝试将数据发布到上面的 web url,我还尝试将其发布到静态 json 文件,认为它可能会以某种方式托管文件使用 npm install -g json-server 命令,但我发现使用本地文件时找不到 json 文件,如果我尝试发布到上面的 url,那么它会在控制台日志中显示一个帖子,但我的表用户永远不会更新。谁能告诉我如何让它工作,以便我可以看到我的 POST 数据?
user.service.ts
import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map';
import {Http, Headers} from '@angular/http';
import {User} from './user';
@Injectable()
export class UserService{
constructor(private _http:Http){
}
getUsers(){
return this._http.get('http://localhost:4200/users')
.map(res=>res.json());
}
addUser(post){
return this._http.post('http://localhost:4200/users', post)
.map(res=> res.json());
}
}
form.component.ts
import { Component, OnInit } from '@angular/core';
import {UserService} from '../users.service';
import {Http} from '@angular/http';
import {Router} from '@angular/router';
import {FormGroup, FormControl} from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css'],
providers: [UserService]
})
export class FormComponent implements OnInit{
private user;
private _users;
constructor(
private _userService:UserService
){
}
userForm = new FormGroup({
name: new FormControl(),
username: new FormControl(),
email: new FormControl(),
address: new FormGroup({
street: new FormControl(),
suite: new FormControl(),
city: new FormControl(),
postalcode: new FormControl()
})
});
onSubmit(){
this._userService.addUser(this.userForm.value)
.subscribe(res => {
this.user = res;
console.log(res);
})
}
}
【问题讨论】:
-
你启动服务器了吗?此外,您的网址似乎仍然指向在线版本,而不是您自己的本地版本。
-
我已经尝试将它指向两者。我把上面的代码贴在网上,但我也试过指向app/users.json,这是本地文件,但是得到了找不到它的消息。它与 GET 请求的路径相同,所以我知道路径是正确的。我更新了上面的代码以反映本地 json 文件
标签: json angular angular2-forms