2017-09-11 33 views
3

我試圖在使用已編碼的JSON服務器時運行Angular 4應用程序。我遇到的問題是我不明白在端口4200上運行的Angular 4應用程序如何可以在端口3000上同時與JSON服務器通信。該應用程序是一個CRUD的例子,但是當我嘗試添加一些東西時,什麼也不會發布。使用JSON服務器運行Angular 4應用程序

這是我article.service.ts:

@Injectable() 
export class ArticleService { 
    //URL for CRUD operations 
    articleUrl = "http://localhost:3000/articles"; 
    //Create constructor to get Http instance 
    constructor(private http:Http) { 
    } 
    //Fetch all articles 
    getAllArticles(): Observable<Article[]> { 
     return this.http.get(this.articleUrl) 
       .map(this.extractData) 
       .catch(this.handleError); 

    } 
    //Create article 
    createArticle(article: Article):Observable<number> { 
     let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: cpHeaders }); 
     return this.http.post(this.articleUrl, article, options) 
       .map(success => success.status) 
       .catch(this.handleError); 
    } 
    //Fetch article by id 
    getArticleById(articleId: string): Observable<Article> { 
     let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: cpHeaders }); 
     console.log(this.articleUrl +"/"+ articleId); 
     return this.http.get(this.articleUrl +"/"+ articleId) 
       .map(this.extractData) 
       .catch(this.handleError); 
    } 
    //Update article 
    updateArticle(article: Article):Observable<number> { 
     let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: cpHeaders }); 
     return this.http.put(this.articleUrl +"/"+ article.id, article, options) 
       .map(success => success.status) 
       .catch(this.handleError); 
    } 
    //Delete article  
    deleteArticleById(articleId: string): Observable<number> { 
     let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: cpHeaders }); 
     return this.http.delete(this.articleUrl +"/"+ articleId) 
       .map(success => success.status) 
       .catch(this.handleError); 
    } 
    private extractData(res: Response) { 
     let body = res.json(); 
     return body; 
    } 
    private handleError (error: Response | any) { 
     console.error(error.message || error); 
     return Observable.throw(error.status); 
    } 
} 

這是我db.json:

{ 
    "articles": [ 
     { 
     "id": 1, 
     "title": "Android AsyncTask Example", 
     "category": "Android" 
     } 
    ] 
} 
+0

請編輯您的問題並在您使用服務的地方添加代碼。 – n00dl3

回答

1

我對端口5005上運行的後端服務,並在4200上運行的應用程序,在爲了「交談」相互我已經建立了proxy.config.json文件看起來像這樣

{ 
    "/api/*":{ 
    "target":"http://localhost:5005", 
    "secure": false, 
    "logLevel": "debug" 
    } 
} 

,當I S錯過我的應用程序我運行 ng serve -open --sourcemap=false --proxy-config proxy.config.json命令。

你也可以嘗試做這樣的事情。

+0

那麼,你的代碼可以工作,但是應用程序在創建對象時會停頓,所以我不確定它是否仍然連接到JSON服務器。 – azmatrix

相關問題