如何以“嵌套订阅”模式返回第二个值?

时间:2019-04-01 09:09:37

标签: angular subscribe

在Angular 7应用程序中,我有服务的方法部分,该方法必须返回Observable才能由某些客户端代码进行订阅。

此方法建立在“嵌套订阅”模式上,关于我所读到的BTW的内容,这是一种反模式。但是,老实说,我对Angular不够熟练,无法替代它。

代码看起来大致如下:

public signIn(customer): Observable<Customer> {
        return this.apiProvider.getCustomerTokens(customer)
            .pipe(map(token => {
                return this.apiProvider.getCustomer(token)
                    .subscribe(customerData => {
                        // some code here...
                    });
            }));
    }

这会导致同步问题,这可能是由于尽管客户端代码实际上需要在第一个return之前解释第二个 class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin { AnimationController _controller; Animation<double> _animation; var _duration = const Duration(milliseconds: 3000); @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: _duration, )..addListener(() { setState(() {}); }); _animation = new Tween<double>(begin: 20.0, end: 400.0).animate(_controller); _controller.forward(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Stackoverflow'), ), body: Center( child: AnimatedContainer( duration: _duration, height: _animation.value, width: 200, color: Colors.amber, ), )); } } ,但需要预订 second 返回值。

关于如何使其正常运行的任何想法?

谢谢

2 个答案:

答案 0 :(得分:0)

使用switchMap。

public signIn(customer): Observable<Customer> {
        return this.apiProvider.getCustomerTokens(customer)
            .pipe(switchMap(token => this.apiProvider.getCustomer(token))
    }

然后,订阅返回的observable。

答案 1 :(得分:0)

您可以在下面尝试使用switchmap等待第一个响应,然后再执行另一个

A = [{
 'd_id' => '1',
 'name' => 'abc',
 'mapping' => 'xyz'
},
{
 'd_id' => '2',
 'name' => 'abc',
 'mapping' => 'xyz'
},
{
 'd_id' => '3',
 'name' => 'abc',
 'mapping' => 'xyz'
}]