在Angular2中订阅不起作用

时间:2017-12-05 20:06:14

标签: javascript angular typescript

我对Angular2中的subscribe有疑问,请帮助我......

我有两个函数,第一个函数返回值,第二个函数必须使用它。

这是我的例子

这是第一个函数,一切正常,工作正常,它返回this.mapCenter,这个值我以后需要

   prevId () {
     let name, id, lat, lng;
     this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {

        if (this.previousUrl !== undefined) {

          this.clickedMarker = this.previousUrl.substring(10);

          for (let i = 0; i < this.data.length; i++) {
            if(this.data[i].code === this.clickedMarker) {
              id = this.data[i].code;
              name = this.data[i].displayName;
              lat = parseFloat(this.data[i].lat);
              lng = parseFloat(this.data[i].lng);
              this.mapCenter = L.latLng([lat, lng]);
            }
          }
          // Open up the popup, when user comes back
          let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
          let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
          myMarker.bindPopup(mark).openPopup();
        } else {
          console.log('not yet');
          this.mapCenter = L.latLng([48.145, 11.58]);
        }
        this.previousUrl = (e as NavigationEnd).url;
        return this.mapCenter;

      });
  }

现在我需要使用这个值。 mapCenter作为第二个函数的参数。

this.mapInitialize(this.mapCenter);

这两个功能都在ngOnInit

  ngOnInit() {
    this.prevId();

    this.mapInitialize(this.mapCenter);
  }

我尝试了this.prevId().subscribe之类的内容,但收到错误subscribe doesn't exist on type void ...

UPD:我无法在第一个功能中分配第二个功能。我以后需要第二个功能,如果我将它分配到另一个功能中,一切都会刹车

3 个答案:

答案 0 :(得分:0)

订阅不会返回值。它的下一个界面是:

(value: any) => void

它只接收值。这是异步事件处理的工作方式。就目前而言,您需要移动mapInitialize函数:

prevId () {
 let name, id, lat, lng;
 this.router.events
  .filter(event => event instanceof NavigationEnd)
  .subscribe(e => {

    if (this.previousUrl !== undefined) {

      this.clickedMarker = this.previousUrl.substring(10);

      for (let i = 0; i < this.data.length; i++) {
        if(this.data[i].code === this.clickedMarker) {
          id = this.data[i].code;
          name = this.data[i].displayName;
          lat = parseFloat(this.data[i].lat);
          lng = parseFloat(this.data[i].lng);
          this.mapCenter = L.latLng([lat, lng]);
        }
      }
      // Open up the popup, when user comes back
      let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
      let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
      myMarker.bindPopup(mark).openPopup();
    } else {
      console.log('not yet');
      this.mapCenter = L.latLng([48.145, 11.58]);
    }
    this.previousUrl = (e as NavigationEnd).url;
    this.mapInitialize(this.mapCenter);

  });
}

ngOnInit() {
  this.prevId();
}

这是使其工作的最快捷方式,但它可以大大清理。

答案 1 :(得分:0)

你的第一个方法必须是一个Observable方法。像贝娄:

public getByProvinceId(provinceId: number): Observable<CityModel[]> {

    const url = this.urlBase + `city/province/${provinceId}`;
    return this.http.get(url, this.options)
      .map((response: Response) => {
        const retVal = <CityModel[]>response.json();
        return retVal;
      });
  }
第二种方法中的

和(例如)使用subscribe:

this.getByProvinceId(this.ProvinceId)
            .subscribe(result => {
                if (result.succeeded == true) {
                    this.regCities = result.returnValue;
                }
                else {
                    this.messageBox.ShowError(result.responseMessage);
                }
            });

答案 2 :(得分:0)

prevId()方法的一个问题是它的可复制性太多了,

  • 计算this.mapCenter
  • 调用弹出窗口
  • 设置this.previousUrl
  • 的新值


您可能要做的第一件事是提取mapCenter的逻辑,就像这样

getMapCenter() {
  let mapCenter = { name: '', id: '', lat: 48.145, lng: 11.58, latLng: null };
  if (this.previousUrl === undefined) {

    this.clickedMarker = this.previousUrl.substring(10);

    for (let i = 0; i < this.data.length; i++) {
      if(this.data[i].code === this.clickedMarker) {
        id = this.data[i].code;
        mapCenter.name = this.data[i].displayName;
        mapCenter.lat = parseFloat(this.data[i].lat);
        mapCenter.lng = parseFloat(this.data[i].lng);
      }
    }
  } else {
    console.log('not yet');
  }
  mapCenter.latLng = L.latLng([mapCenter.lat, mapCenter.lng]);
  return mapCenter
}


我们还可以提取弹出逻辑

showPopup(mapCenter) {
  // Open up the popup, when user comes back
  let myMarker = new L.Marker(mapCenter.latLng, {icon: mapUI.marker}).addTo(this.map);
  let mark = this.popupHtmlGenerate( mapCenter.name, mapCenter.id, mapCenter.latLng );
  myMarker.bindPopup(mark).openPopup();
}


现在prevId()只能做它标签上的内容

prevId () {
  this.router.events
    .filter(event => event instanceof NavigationEnd)
    .subscribe(e => {
      this.previousUrl = (e as NavigationEnd).url;
    });
  }


现在我们可以看到this.mapCenter不依赖于router.events的订阅价值,因此它可以同步运行并传入this.mapInitialize()

ngOnInit() {
  const mapCenter = this.getMapCenter();
  this.mapCenter = mapCenter.latLng;
  this.showPopup(mapCenter);
  this.prevId();
  this.mapInitialize(this.mapCenter);
}