加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:02:27 所属栏目:安全 来源:网络整理
导读:我的情况: 我有一个组件显示tile,每个tile表示一个数组中的对象,该数组通过ngfor循环. 单击一个图块时,我想将该对象传递给另一个组件,该组件负责在可以修改的字段中显示该对象的所有属性. 我尝试过的: 在做了一些研究并发现多个帖子向我展示了如何为父子层
我的情况:

我有一个组件显示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);
    });
  }
 }

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读