Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Angular 2在从Observable catch调用函数时发送此消息_Javascript_Angular_Typescript_Observable - Fatal编程技术网

Javascript Angular 2在从Observable catch调用函数时发送此消息

Javascript Angular 2在从Observable catch调用函数时发送此消息,javascript,angular,typescript,observable,Javascript,Angular,Typescript,Observable,我有这个(简化的)服务: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); } getAll() {

我有这个(简化的)服务:

@Injectable()
export class DataService {
    constructor(protected url: string) { }

    private handleError(error: Response) {
        console.log(this.url);
        return Observable.throw(new AppError(error));
    }

    getAll() {
        return this.http.get(this.url)
            .map(response => response.json())
            .catch(this.handleError);
    }
}
handleError
函数中,this.url未定义。为什么?从
catch
调用
this.handleError
时,如何获取当前实例

我不认为这是经常使用的
this
Observable
在尝试应用通常的JS解决方案时会给我带来很多错误


前面谢谢。

角度服务的构造函数不同于您知道的经典构造函数。而且该服务不应该由您自己实例化。Angular本身将实例化您的服务,并通过依赖项注入传递实例。因为您不能实例化它,而且Angular应该为您这样做,所以它的参数列表中只能有服务或其他可注入项,这样Angular就会知道它,并且能够将其实例传递给构造函数

如果你想给你的
url
属性分配一些东西,那么你必须添加单独的方法来为你做这件事,或者只是公开url并直接分配给它

但是为了让它存在,我建议您将代码更改为以下内容

    return this.http.get(this.url)
        .map(response => response.json())
        .catch(error => this.handleError(error));

请记住,lambda表达式(箭头函数)被添加到ES6中,特别是针对上下文问题。在ES6中,它们比功能更轻。但是TypeScript编译器将所有这些转换为函数。所以这里唯一的效果是上下文没有改变。但是我希望将来它们将被翻译成lambdas,并且更加有效。

catch(this.handleError.bind(this))
或者使用箭头函数,
catch(()=>this.handleError)
。url从哪里来?服务使用依赖注入(DI)。DI如何知道传入url?可能是@JeremyBelolo的副本是的,您需要在中添加正确的类型或至少是参数,抱歉:
.catch(err=>this.handleError(err))
。如果只有使用
super
扩展此参数的其他服务才提供这样的自定义参数,则添加此参数是不正确的?无论如何,我可以向它显示任何可用的DI服务,而不是自定义参数,例如
http
,它们也是
undefined
。当然,如果你想在那里使用它,@cartant的答案是正确的。但我说的不是这个。handleError,而是把获取url作为DI的一部分。但我更喜欢在那里使用lambda,而不是将其绑定到handleError