Angular 在服务调用2之后获取未定义的值

Angular 在服务调用2之后获取未定义的值,angular,http,typescript,angular-services,Angular,Http,Typescript,Angular Services,我在angular 2中得到一个变量的未定义值。我有一个调用服务的函数,该服务提供数据来初始化变量,现在我将这个变量提供给另一个执行get http请求的函数。和get request in无法作为undefined中的变量进行处理 代码: 您的function1似乎执行了一个异步调用,用于将数据设置为该值。变量如果是这种情况,则必须等待异步函数完成,然后才能转到function2 尽力 variable:any; constructor(private http: Http, private

我在angular 2中得到一个变量的未定义值。我有一个调用服务的函数,该服务提供数据来初始化变量,现在我将这个变量提供给另一个执行get http请求的函数。和get request in无法作为undefined中的变量进行处理

代码:


您的function1似乎执行了一个异步调用,用于将数据设置为该值。变量如果是这种情况,则必须等待异步函数完成,然后才能转到function2

尽力

variable:any;
constructor(private http: Http, private serviceOne: ServiceOne){
function1();    //service call to get data
}

function1(){
yourAsyncCall(). subscribe(res=>{
this.function2(res);
}) 
}

function2(variable){
this.variable=variable ;
//Use variable in your http requeat
}

如何使其同步@GiliIt取决于您的数据源,但若它是从服务器获取的,那个么它就不能同步。http请求本质上是异步的。为什么您希望它是同步的?
variable:any;
constructor(private http: Http, private serviceOne: ServiceOne){
function1();    //service call to get data
}

function1(){
yourAsyncCall(). subscribe(res=>{
this.function2(res);
}) 
}

function2(variable){
this.variable=variable ;
//Use variable in your http requeat
}