角度订阅返回对象对象不是字符串

时间:2018-03-13 17:22:26

标签: angular typescript async-await frontend observable

我有这样的功能。

public static getStepImage(step, connection) {
    switch (step) {
        case label.ASSIGN:
            return label.IMAGE_DIRECTORY + "Assign.svg";
        case E2wStepType.NOTIFICATION:
            return label.IMAGE_DIRECTORY + "Notification.svg";
        case E2wStepType.SERVICE:
                return connection.getConnection(step.connection);
        default:
            return label.IMAGE_DIRECTORY + "Empty.svg";
    }
}

getStepImage

中执行的_createRectangularStep函数
`private static _createRectangularStep(steps, connectionRepoService: E2wConnectionRepoService) {
  let rectSteps = steps.filter(
        step => editUnit.isRectangularStep(step) || editUnit.isUnknownStep(step) ? step : null);
  rectSteps.append("image")
            .attr('x', step => LabelProvider.getStepImageInset(step).x)
            .attr('y', step => LabelProvider.getStepImageInset(step).y)
            .attr("xlink:href",  step => LabelProvider.getStepImage(step, connectionRepoService).subscribe(
                    (val: any) => {
                        console.log(val.icon);
                        return val.icon;
                    }
            ))
}

`

console.log(val.icon)显示images/logo.svg但attr href获取[object Object]

1 个答案:

答案 0 :(得分:3)

// Your code that isn't working:
/*public static getData(data, connection) {
  switch (data) {
    case 'user':
      return "this is user";
    case 'admin':
      let tmp: string;
      connection.getConnection(step).subscribe(conn => {
        tmp= conn.name;
      });
      return tmp;
    default:
      return 'empty';
  }
}*/

// How you need to rewrite your code (for RxJS v2-4):
import { Observable } from 'rxjs/Observable';
// (for RxJS v5):
import { of } from 'rxjs/observable/of';

public static getData(data, connection) {
  switch (data) {
    case 'user':
      // (RxJS v2-4)
      return Observable.of({ name: "this is user" });
      // (RxJS v5)
      // return of({ name: 'this is user' });
    case 'admin':
      return connection.getConnection(step);
    default:
      // (RxJS v2-4)
      return Observable.of({ name: 'empty' });
      // (RxJS v5)
      // return of({ name: 'empty' });
  }
}

// Based on your edits, here is how I would rewrite your function. I can't guarantee that it will work perfectly because these two libraries handle data so differently:
private static _createRectangularStep(steps, connectionRepoService: E2wConnectionRepoService) {
  steps.append("image")
    .attr('x', step => LabelProvider.getStepImageInset(step).x)
    .attr('y', step => LabelProvider.getStepImageInset(step).y)
    .attr("xlink:href",  step => {
      let returnValue = '';
      LabelProvider.getStepImage(step, connectionRepoService)
        .subscribe(
          (val: any) => {
            returnValue = val;
          }
        );
      return returnValue;
    });
}