订阅不存在“订阅"类型 [英] Subscribe does not exist of type 'Subscription'

查看:58
本文介绍了订阅不存在“订阅"类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angualr 2的新手.我正在申请一份小型练习.我为用户登录时提供了身份验证服务.这是登录功能.

I am new to angualr 2. And I am making a small application for practice. I have a service for authentication of users when they log in. And here is it's login function.

login(email:string, password:string){

        var loginrul="https://filing.herokuapp.com/api/v1/auth/login/";
        return this.http.post(loginrul,JSON.stringify({  password: password,email: email }),
            {headers:new Headers({'Content-Type':'application/json'})}
            ).map(res=>res.json()).
            subscribe(
                data => localStorage.setItem('id_token',data.auth_token),
                error=>console.log(error)
            );
    }

当我在组件angualr中调用此函数时,出现错误消息类型'Subscription'上不存在属性订阅.

When I call this function in component angualr gives error that "Property subscribe does not exist on type 'Subscription'.

doLogin(event) {
        console.log(event);
        console.log(this.loginForm.value);


        let formData = this.loginForm.value;
        let email = this.loginForm.controls.email.value;
        let password= this.loginForm.controls.password.value;
        this.auth.login(email,password).subscribe(res =>{
            console.log(res);
            if(res.status===200){
                this.router.navigate(['dashboard']);
            }
        }
        )
    }

我想为什么angular会出现此错误,因为我在登录功能中以及在调用登录功能时都使用了订阅.请提出一些解决方案或替代方法来实现我要在登录功能中实现的结果.

I think why angular is giving this error because i am using subscribe in login function as well as while calling login function. Please suggest some solution or an alternative approach to achieve the result which I am trying to achieve in login function.

推荐答案

您自己对问题的分析是正确的!删除服务中的.subscribe,仅在使用它的组件中使用它.您的服务应在.map运算符之后返回.

Your own analysis of the problem is correct! Remove the .subscribe in your service and only use it in your component where you consume it. Your service should return after the .map operator.

如果您订阅该服务,它将返回一个Subscription而不是一个Observable,这确实是您收到错误的原因.

If you subscribe in the service, it will return an Subscription instead of an Observable, and that's indeed why you are getting your error.

这篇关于订阅不存在“订阅"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆