2016-12-21 1 views
6

각도 유니버설에서 백 엔드와 프런트 엔드간에 통신이 있음을 증명하기 위해 POC를 수행하고 있습니다. 백 엔드에서 heroes.json이라는 JSON 파일을 가지고 있는데 프런트 엔드 서비스 ModelService에서 검색하려면 model.service.ts을 입력하십시오. 내가 getStuff()라는 메소드의 일부 데이터를 얻을 수있는 HTTP 요청을 만들려면json 파일에 대해 각도 2 http GET이 반환됩니다. 404

enter image description here

model.service.ts (프론트 엔드) 내 :

나는이 폴더 구조를 가지고있다.

나는 model.service.ts이있다 :이 오류를 받고 있어요

export class HomeComponent { 

     public data: any = {}; 
     constructor(public modelService: ModelService) { 
     // we need the data synchronously for the client to set the server response 
     // we create another method so we have more control for testing 
     this.universalInit(); 
     } 

     public universalInit() { 

     this.modelService.getStuff().subscribe((data) => { 
      this.data = data; 
     }); 
     } 

: 나는 ModelService.getHeroes를 호출하고 프런트 엔드 구성 요소에서

// domain/feature service 
@Injectable() 
export class ModelService { 
    private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file 
    // This is only one example of one Model depending on your domain 
    constructor(public api: ApiService, public cacheService: CacheService, private http: Http) { 

    } 

    public getStuff(): Observable<any[]> { 
     return this.http.get(this.heroesUrl) 
        .map(this.extractData) 
        .catch(this.handleError); 
    } 

    private extractData(res: Response) { 
    let body = res.json(); 
    return body.data || { }; 
    } 

    private handleError (error: Response | any) { 
    // In a real world app, we might use a remote logging infrastructure 
    let errMsg: string; 
    if (error instanceof Response) { 
     const body = error.json() || ""; 
     const err = body.error || JSON.stringify(body); 
     errMsg = `${error.status} - ${error.statusText || ""} ${err}`; 
    } else { 
     errMsg = error.message ? error.message : error.toString(); 
    } 
    console.error(errMsg); 
    return Observable.throw(errMsg); 
    } 

    // domain/feature service 
    @Injectable() 
    export class ModelService { 
     private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file 
     // This is only one example of one Model depending on your domain 
     constructor(public api: ApiService, public cacheService: CacheService, private http: Http) { 

     } 

     public getStuff(): Observable<any[]> { 
      return this.http.get(this.heroesUrl) 
         .map(this.extractData) 
         .catch(this.handleError); 
     } 

     private extractData(res: Response) { 
     let body = res.json(); 
     return body.data || { }; 
     } 

     private handleError (error: Response | any) { 
     // In a real world app, we might use a remote logging infrastructure 
     let errMsg: string; 
     if (error instanceof Response) { 
      const body = error.json() || ""; 
      const err = body.error || JSON.stringify(body); 
      errMsg = `${error.status} - ${error.statusText || ""} ${err}`; 
     } else { 
      errMsg = error.message ? error.message : error.toString(); 
     } 
     console.error(errMsg); 
     return Observable.throw(errMsg); 
     } 

GET /src/backend/heroes.json 404 3.698 ms - 46 
404 - {"status":404,"message":"No Content"} 
EXCEPTION: 404 - {"status":404,"message":"No Content"} 

/private/var/root/vepo/node_modules/rxjs/Subscriber.js:227 
      throw err; 
      ^
404 - {"status":404,"message":"No Content"} 
[nodemon] app crashed - waiting for file changes before starting... 

내 URL private heroesUrl = "http://localhost:4000/src/backend/heroes.json"; // URL to JSON file 서비스가 잘못되었습니다. 그 폴더 구조를 감안할 때, URL은 무엇이겠습니까? 실제 실행중인 프로젝트, 출력, DIST에 있기 때문에 :

enter image description here

그래서 나는 ModelService.heroesUrl 무엇을 입력 모르겠어요. ModelService.heroesUrl에는 어떤 문자열 값이 필요합니까?

답변

4

당신은 당신의 dist 폴더 클라이언트로 JSON 파일을 넣어 가지고 있고 http://localhost:4000/dist/heroes.json<-- destination where you are putting your json file in dist directory 내가 "assets" 폴더 내 같은 파일 places.json을 넣어

+0

http가 잘 작동하는지 테스트하려면 https://jsonplaceholder.typicode.com/ –

+0

테스트 링크를 이용해 주셔서 감사합니다. 나는 우리가 dist를 실제로 만지지는 않는다고 생각하고 src 앱을 컴파일하고 번역 한 후에는 결과물 일뿐입니다. 이 poc의 핵심은 백 엔드에서 데이터를 가져 와서 백 엔드와 프런트 엔드 간의 연결을 테스트하기 때문에 클라이언트에 json을 넣는 것이 옳지 않은 것처럼 보입니다. – BeniaminoBaggins

+0

dist 폴더를 만든 후에는 이미지와 마찬가지로 모든 링크를 변경해야합니다. dist 콘텐츠를 서버에 업로드 할 때 거기에 로컬 이미지를 저장해야하기 때문입니다. 이 문제에 많은 시간을 쏟았다. 실제로 귀하의 json 서버에 있어야합니다. –

7

과 후 URL을 변경해야 할 설정 한 URL과 같은 :

places = this.http.request("http://localhost:4200/assets/places.json") 

희망이 정보는 누군가에게 도움이 되길 바랍니다.