typescript “订阅”类型的订阅不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44686959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:39:33  来源:igfitidea点击:

Subscribe does not exist of type 'Subscription'

angulartypescript

提问by Shoaib Iqbal

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.

我是 angualr 2 的新手。我正在制作一个小的练习应用程序。我有一个用户登录时的身份验证服务。这是登录功能。

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

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

当我在组件 angualr 中调用此函数时,会出现“属性订阅不存在于‘订阅’类型上的错误。

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

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.

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

回答by Fredrik Lundin

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

你自己对问题的分析是正确的!删除.subscribe您的服务中的 ,并仅在您使用它的组件中使用它。您的服务应该在.map接线员之后返回。

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

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