2017-09-11 32 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

相关问题