2016-11-16 109 views
0

我還是這個新手,但我試圖發佈我自己的數據到https://jsonplaceholder.typicode.com/users用於學習目的。在頁面的底部,它說使用npm install -g json-server,所以我在我的項目中運行了該命令,並試圖將數據發佈到上面的網址,並且我也試着將它發佈到靜態json文件中,認爲它可能以某種方式託管文件npm install -g json-server命令,但是我知道使用本地文件時沒有找到json文件,如果我嘗試發佈到上面的url,那麼它會顯示一個帖子在控制檯日誌中,但我的表與用戶從不更新。任何人都可以告訴我如何得到這個工作,所以我可以看到我的POST數據?發佈到json服務器問題

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

}) 

} 

} 
+0

您是否啓動服務器?此外,您的網址似乎仍然指向在線版本,而不是您自己的本地版本。 –

+0

我試過把它指向兩者。我發佈了上面的代碼以指向在線,但我也試過將它指向app/users.json,它是本地文件,但得到消息說它沒有找到。它與GET請求的路徑相同,所以我知道路徑是正確的。我更新了上面的代碼以反映本地json文件 – user6680

回答

0

你不需要點,現在你讓服務器運行到App/users.json。每documentation,你可以發佈到http://localhost:3000/users

+0

我更新了上面的代碼以反映您的建議,但它現在不在GET中提取任何json數據,並且users.json位於app目錄中。錯誤:意外的標記<位於0的JSON中 – user6680

+0

您可能想要檢查服務器是否一切正常,它可能會返回錯誤。 –

0

我相信你錯過了公共服務(什麼是合理的)

Note: the resource will not be really created on the server but it will be faked as if.

,因爲你已經在本地安裝,只需要運行:

$ jsonplaceholder

後更換您的網址,主機名Angular to http://localhost:3000

+0

我運行了npm install -g json-server命令(這是你運行jsonplaceholder的意思嗎?)它現在不會在GET中提取任何json數據,而users.json在app目錄中。錯誤:意外的標記<在JSON中的位置 – user6680

+0

抱歉,我認爲你運行了(npm install -g jsonplaceholder),因爲它在文檔中寫入後,你應該能夠使用(jsonplaceholder)作爲命令,如(gulp或任何其他npm libs全局安裝),json-server是jsonplaceholder使用的lib – 2oppin