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

时间:2018-02-15 12:15:02

标签: angular typescript

我想在我的angular类中编写一个泛型方法,从一个observable返回一个值并设置一些类属性。我的代码类似于下面的

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;

}
}

方法调用后,我的类属性都是undefined。完整功能可以使用localVar。任何想法我们怎么可能从这样的函数调用返回值?

1 个答案:

答案 0 :(得分:0)

根据您的示例,应进行以下修改:

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);
        }
    )
}
}

现在进行解释:属性不能获取Observable值,这就是为什么您必须订阅要返回所需值的函数的原因。如果你有任何问题,请问我,我会尽力解释。