微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 4 – 将对象从一个组件传递到另一个组件(没有父 – 子层次结构)

我的情况:

我有一个组件显示tile,每个tile表示一个数组中的对象,该数组通过ngfor循环.
单击一个图块时,我想将该对象传递给另一个组件,该组件负责在可以修改的字段中显示该对象的所有属性.

我尝试过的:

在做了一些研究并发现多个帖子向我展示了如何为父子层次结构实现这一点以及一些帖子解释为了实现想要的功能需要使用共享服务,我决定尝试设置这样的服务.

然而,我似乎没有得到的是当我应该导航到不同的路线.似乎导航在早期找到了位置,因为在详细信息组件中检索它时,传递给服务的对象是未定义的.

我的代码

显示切片的组件具有以下功能,可将单击的对象传递给共享服务:

editPropertyDetails(property: Property) {
    console.log('Edit property called');

    return new Promise(resolve => {
      this.sharedPropertyService.setPropertyTodisplay(property);
      resolve();
    }).then(
      () => this.router.navigate(['/properties/detail'])
    )
  }

共享服务具有设置属性对象的功能和检索它的功能,如下所示:

@Injectable()
export class SharedPropertyService {
  // Observable
  public propertyTodisplay = new Subject<Property>();

  constructor( private router: Router) {}

  setPropertyTodisplay(property: Property) {
    console.log('setPropertyTodisplay called');
    this.propertyTodisplay.next(property);
  }

  getPropertyTodisplay(): Observable<Property> {
    console.log('getPropertyTodisplay called');
    return this.propertyTodisplay.asObservable();
  }
}

最后是必须接收被单击的对象但获取未定义对象的detail组件:

export class PropertyDetailComponent implements OnDestroy {

  property: Property;
  subscription: Subscription;

  constructor(private sharedPropertyService: SharedPropertyService) {
        this.subscription = this.sharedPropertyService.getPropertyTodisplay()
          .subscribe(
            property => { this.property = property; console.log('Detail Component: ' + property.description);}
          );
  }

  ngOnDestroy() {
    // When view destroyed,clear the subscription to prevent memory leaks
    this.subscription.unsubscribe();
  }
}

提前致谢!

解决方法

请尝试以下示例:

第1步:创建服务[DataService]

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {
  private userIdSource = new BehaviorSubject<number>(0);
  currentUser = this.userIdSource.asObservable();

  private orderNumSource = new BehaviorSubject<number>(0);
  currentOrder = this.orderNumSource.asObservable();

  constructor() { }

  setUser(userid: number) {
    this.userIdSource.next(userid)
  }

   setorderNumber(userid: number) {
    this.orderNumSource.next(userid)
  }
}

第2步:在登录组件中设置值

import { Component } from '@angular/core';
import { DataService } from "../services/data.service";

@Component({
  selector: 'app-login',templateUrl: './login.component.html',styleUrls: ['./login.component.css'] 
})
export class LoginComponent {
  constructor( private dataService:DataService) {     }
   onSubmit() {
        this.dataService.setUser(1); 
  } 
}

第3步:获取一个组件的价值

import { Component,OnInit } from '@angular/core';
import { DataService } from "../services/data.service";

@Component({
  selector: 'app-shopping-cart',templateUrl: './shopping-cart.component.html',styleUrls: ['./shopping-cart.component.css']
})
export class ShoppingCartComponent implements OnInit {
  userId: number = 0;
  constructor(private dataService: DataService) { }
  ngOnInit() {
    this.getUser();
 }
  getUser() {
    this.dataService.currentUser.subscribe(user => {
      this.userId = user
    },err => {
      console.log(err);
    });
  }
 }

注意:在页面刷新时,该值将丢失.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐