我试图在尝试使用已编码的JSON服务器时尝试运行Angular 4应用程序。我遇到的问题是,我不明白在端口4200上运行的Angular 4应用程序如何能够同时在端口3000上与JSON服务器通信。该应用程序是CRUD的一个示例,但是当我尝试添加某些内容时,没有任何内容发布。
这是我的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 :(得分:2)
我有在端口5005上运行的后端服务,以及在4200上运行的应用程序,以便&#34;通话&#34;我已经设置了proxy.config.json
文件,看起来像这样
{
"/api/*":{
"target":"http://localhost:5005",
"secure": false,
"logLevel": "debug"
}
}
当我服务我的应用程序时,我跑了
ng serve -open --sourcemap=false --proxy-config proxy.config.json
命令。
你也可以尝试这样做。