简体   繁体   English

如何从内部具有Observable订阅的angular函数返回值

[英]How to return value from function in angular which has Observable subscription inside

I want to write a generic method in my angular class to return a value from an observable and set a number of class properties. 我想在我的角度类中编写一个通用方法,以从可观察值返回值并设置许多类属性。 My code resembles below 我的代码如下

export class SomeServiceClass implements OnInit {

someProperty1: someObject;
someProperty2: someObject;
somePropertyN: someObject;

ngOnInit() {
     this.someProperty1 = getValueFromObservableGenericMethod("value1")
     this.someProperty2 = getValueFromObservableGenericMethod("value2")
     this.somePropertyN = getValueFromObservableGenericMethod("valueN")

    console.log(someProperty1); // undefined
    console.log(someProperty2); // undefined
    console.log(someProperty3); // undefined
}


getValueFromObservableGenericMethod(someIncomingString: string): someObject {

    let localVar: someObject;

    this.anotherServiceClass.subscribe(
        data => {
            localVar = data;
        },
        () => {
            return localVar;;
            console.log(localVar);
        }
    )

    return localVar;

}
}

My class properties are all undefined after the method call. 方法调用后,我的类属性都undefined The localVar is available though on complete function. localVar可虽然在功能齐全。 Any ideas how can we possibly return values from such a function call? 有什么想法我们怎么可能从这样的函数调用中返回值?

Working on your example, the following modifications should be made: 在处理您的示例时,应进行以下修改:

export class SomeServiceClass implements OnInit {

    someProperty1: someObject;
    someProperty2: someObject;
    somePropertyN: someObject;

    ngOnInit() {
        getValueFromObservableGenericMethod("value1").subscribe(result => {
            this.someProperty1 = result;
            console.log(someProperty1); // not undefined anymore            
        }
}


getValueFromObservableGenericMethod(someIncomingString: string): Observable<someObject> 
{

    let localVar: someObject;
    // notice that I changed subscribe with map
    return this.anotherServiceClass.map(
        data => {
            localVar = data;
        },
        () => {
            return localVar;;
            console.log(localVar);
        }
    )
}
}

Now to get to explanations: A property cannot take an Observable value, that's why you will have to subscribe to the function that you want to return the desired value. 现在开始解释:一个属性不能采用Observable值,这就是为什么您必须订阅要返回所需值的函数的原因。 if you have anymore questions just ask and I will try my best to explain. 如果您还有其他问题,请提出,我会尽力解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM