2017-10-21 4 views
0

Observables를 처음 사용했습니다. 그래서 여기 내가 내부의 recipeList를 인쇄 할 때 내 문제는 내 코드변수에 데이터를 등록 할 수 없습니다.

recipesList:Recipe[]; 


private recipes; 
constructor(private shoppingService:ShoppingListService,private http:Http){ 
    this.getRecipesFromUrl().subscribe((data)=>{ 
    this.recipesList=data; 
    console.log(this.recipesList);//printing array containing recipes 
    }); 
    console.log(this.recipesList);//printing undefined 
} 

인 나는 그것의 표시 정의되지 않은 외부 인쇄하고 때 내가 조리법을 받고 있지만 오전에 가입. recipeList에 데이터를 저장하는 방법 다른 방법으로도 데이터에 액세스 할 수 있습니다.

+1

CONSOLE.LOG을 할 수있는 구독하고 기다려야한다. 데이터가로드 된 후에 recipeList에 대한 액세스가 필요한 모든 메소드를 호출해야합니다. – LLai

+0

복제본에서와 같이 콜백 (구독) 내부에서 원하는/원하는 것을해야합니다. – Alex

답변

0

코드의 문제점은 getRecipesFromUrl이 비동기 작업이라는 점입니다. 완료 될 때까지 로그 작업이 실행되었을 것이므로 recipesList는 정의되지 않습니다. 데이터가

도착까지 당신은 항상 당신은 데이터를 가져 오는 있기 때문에 데이터에 액세스 할 수 없습니다 구독가 비동기의 외부에서이

recipesList: Observable<Array<Recipe>>; 

constructor(private shoppingService:ShoppingListService, private http:Http) { 
    this.recipesList = this.getRecipesFromUrl(); 

    //Subscribe and handle data when it arrives 
    this.recipesList.subscribe((recipes) => { 
     console.log("Recipes", recipes); 
    } 
} 

list() { 
    //Subscribe here too 
    this.recipesList.subscribe((recipes) => { 
     console.log("Recipes", recipes); 
    } 
} 
}