简体   繁体   English

使用BehaviourSubject,对象可能是“未定义”的

[英]Object is possibly 'undefined' with BehaviourSubject

I have a BehaviourSubject like: 我有一个BehaviourSubject像:

public _position: BehaviorSubject<Position | undefined> = new BehaviorSubject(undefined);
public position$: Observable<Position | undefined> = this._position.asObservable();
public get position() {
  return this._position.getValue();
}

which I am trying to use like so: 我试图这样使用:

this.position$.subscribe((position) => {
  if (typeof position !== 'undefined') {
    let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  }
});

but no matter what I try, I continue to see the Typescript error: 但无论我如何尝试,我仍然会看到Typescript错误:

[ts] Object is possibly 'undefined'. [ts]对象可能是'undefined'。

for position.coords.latitude and position.coords.longitude . 用于position.coords.latitudeposition.coords.longitude

I don't understand. 我不明白 I've specified that the type can be either Position or undefined . 我已经指定类型可以是Positionundefined I've given it an initial undefined value. 我给了它一个初始的undefined值。 I've also guarded the variable with typeof position !== 'undefined' . 我还使用typeof position !== 'undefined'保护变量。 What's going on? 这是怎么回事?

TypeScript sometimes gets its knickers in a twist over nothing.. TypeScript有时会一无所获。

can you try 你能试一下吗

this.position$.subscribe((position) => {
  if (position && position.coords) {
    let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  }
});

Not exactly sure why typescript is showing that error, but the code can be made cleaner: 不确定为什么打字稿会显示该错误,但是可以使代码更简洁:

If you use rxjs > 5 you may have to rewrite the filter and map 如果您使用rxjs> 5,则可能必须重写过滤器并映射

public _position: BehaviorSubject<Position> = new BehaviorSubject(null);
public position$: Observable<Position> = this._position.asObservable();
public get position() {
  return this._position.getValue();
}

this.position$
    .filter(Boolean)
    .map(position => position.coords)
    .subscribe((coords) => {
        let latLng = new google.maps.LatLng(coords.latitude, coords.longitude);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM