打字稿对象返回数组对象值错误[角度]

时间:2020-03-15 17:46:54

标签: javascript arrays angular typescript angular7

我收到一个奇怪的错误,当我控制台记录我的数组值时,它返回为[object Set]。我不确定这是否在组件或服务中发生,但我没有将对象作为值。

这是从组件调用deleteRow函数并将其传递给服务时发生的。

view.component.ts

    @Component({
  templateUrl: "viewpage.component.html"
})
export class ViewpageComponent implements AfterViewInit, OnInit, OnDestroy {
  viewData: any;
  viewName: string;
  viewTag: number;
  fetchedData: any;
  dataSource: ViewDataSource;
  pageSizeOptions: number[] = [10, 20, 50];

  defaultSortCol = "1";

  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  selection = new SelectionModel<TableRow>(true, []);
  displayedColumns: string[] = [];

  navSub: any;
  primaryTableValue: any;

  constructor(
    private actionService: ActionService,
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
    // Init the component the first time it is navigated to.
    this.initData();
    // Subscribe to the router, so that any new navigation to this component loads new data.
    this.navSub = this.router.events.subscribe((e: any) => {
      if (e instanceof NavigationEnd) {
        this.initData();
      }
    });
  }

  initData() {
    this.viewTag = +this.route.snapshot.paramMap.get("tag");
    this.dataSource = new ViewDataSource(this.actionService);

    // if (this.viewData) {
    //   console.log(this.viewData);
    // }

    // Load the View from the DataSource with default params
    this.dataSource.loadView(this.viewTag, 0, 10, this.defaultSortCol, "asc");

    // Subscribe to the View in the DataSource
    this.dataSource.view.subscribe(x => {
      if (x.ActionName) {
        x.ColumnIds.unshift("9");
        this.viewData = x;
        this.fetchedData = this.viewData.TableData;
        this.primaryTableValue = (this.viewData.ViewData.DbrAction.PrimaryTable);
      }
    });
  }

  ngAfterViewInit() {
    // After sorting, jump back to first page of newly sorted data.
    this.sort.sortChange.subscribe(() => {
      this.paginator.pageIndex = 0;
    });
    // Sort changes and pagination events should reload the page.
    merge(this.sort.sortChange, this.paginator.page)
      .pipe(tap(() => this.loadPage()))
      .subscribe();
  }

  loadPage() {
    this.dataSource.loadView(
      this.viewTag,
      // '',
      this.paginator.pageIndex,
      this.paginator.pageSize,
      this.sort.active,
      this.sort.direction
    );
  }

  /** Whether the number of selected elements matches the total number of rows. */
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.view['source']['value'].TableData;
    return numSelected === numRows.length;
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    this.isAllSelected()
      ? this.selection.clear()
      : this.dataSource.view['source']['value'].TableData.forEach((row: TableRow) =>
          this.selection.select(row)
        );
  }

  // Delete row functionality

  deleteRow() {

    this.selection.selected.forEach(item => {
      const index: number = this.dataSource.view['source']['value'].TableData.filter (
        (d: TableRow) => d === item
      );
      this.dataSource.view['source']['value'].TableData.splice(index, 1);
      this.dataSource = new ViewDataSource(this.dataSource.view['source']['value'].TableData);
    });
    this.selection = new SelectionModel<TableRow>(true, []);
    this.actionService.deleteRow(this.selection, this.primaryTableValue).subscribe(response => {
      console.log("Success!");
    });
  }

view.service.ts

    @Injectable({ providedIn: 'root' })
export class ActionService {

  private actionSource = new BehaviorSubject<any>([]);
  currentAction = this.actionSource.asObservable();

  private refNumSubject = new BehaviorSubject<any>([]);
  currentRef = this.refNumSubject.asObservable();

  // private dataSource = new BehaviorSubject<any>([]);
  // currentPrimaryNumber = this.dataSource.asObservable();

  currentRefNumber: number;

  // This is for saving states of views:
  public stateMap: Map<string, ActionState>;
  public refNumber: number;
  viewData: any;

  constructor(private http: HttpClient, private router: Router) {
    // Init the stateMap
    this.stateMap = new Map<string, ActionState>();
    this.refNumber = 0;
  }
  // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  // Loads a page of an Action after retrieving data from the API.
  // ##BOOKMARK
  loadPage(actionTag: number, pageIndex: number, pageSize: number, sortCol: string, sortDirection: string): Observable<any> {
    let user = JSON.parse(localStorage.getItem('currentUser'));
    return this.http.post<any>('/actions/actionPage/',
      {
        SessionId: user.userEnv.sessionId,
        ActionTag: { value: actionTag },
        SortDirection: sortDirection,
        SortCol: +sortCol,
        PageIndex: pageIndex,
        PageSize: pageSize,
        Filter: ""
      }).pipe(map(actionData => {

        const actionObj = JSON.parse(actionData);

        // Cacheing stuff:
        // this.refNumSubject.next(this.refNumber);
        // let actionState = new ActionState(this.refNumber++, actionTag, pageIndex, pageSize, +sortCol, sortDirection);
        // this.cacheAction(actionState);
        //

        return actionObj;
      }));
  }

    // Delete Row ##TEST

  deleteRow(selection: any, primaryTable: any): Observable<any> {
    const user = JSON.parse(localStorage.getItem('currentUser'));
    const indices = [selection._selection].map((row: { value: any; }) => `${row}`);

    console.log(`Session Id Value in Service: ` + user.userEnv.sessionId);
    console.log(`Primary Table Value in Service: ` + primaryTable);
    console.log(`Row Selection Value in Service: ` + indices);

    return this.http.post<any>('/actions/deleteRow/',
    {
      sessionId: user.userEnv.sessionId,
      table: primaryTable,
      Tag: indices

    }).pipe(map(deleteRowObject => {

      const deleteRowReturn = JSON.parse(deleteRowObject);

      console.log(`test delete ` + deleteRowReturn);

      return deleteRowReturn;
    }));

  }

1 个答案:

答案 0 :(得分:1)

'[object object]'由于使用+运算符,它调用了对象的toString方法

这样使用:

console.log('scope is ' + scope);
Produced the string scope is [object object]

请使用带有逗号的console.log()方法来打印对象

console.log('scope is', scope)