使用带有Angular 2中的路径的Observable和Subscriber传递数据

时间:2017-01-20 13:08:59

标签: angular angular-routing angular-directive angular-services

我有一个有角度的2应用程序,我正在使用路径在组件之间导航。要在兄弟组件之间传递数据,我正在使用Observable和Subscription模式。但是如何使用路由发送数据(我需要传递对象)

app.component.ts

@Component({
 providers: [DataShareService]
})
....

app.component.html

<router-outlet></router-outlet>

DataShareService

 export class DataShareService {
    // Observable string sources
    private dataSource = new Subject<any>();
    private createdPostSource = new Subject<any>();

    // Observable string streams
    dataSource$ = this.dataSource.asObservable();
    createdPostSource$ = this.createdPostSource.asObservable();
    // Service message commands
    passData(data: any) {
     this.dataSource.next(data);
    }

    passCreatedPostSource(data:IPost[]){
     this.createdPostSource.next(data);
    }

  }

PostListComponent

@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.css']
})
export class PostListComponent implements OnInit {

  private _postUrl: string;
  public posts: IPostList;
  public createPost: string;
  private dataSub: Subscription;

  constructor(private _postService: PostService,
              private _config: ConfigService,
              private  _logger: ErrorLogService,
              private _dataShareService: DataShareService,
              private _router: Router) {
  }


  ngOnInit(): void {
    this._postUrl = this._config.get('postApiRoot');

    this._postService.getPosts(this._postUrl)
      .subscribe(
        result => this.posts = result,
        error => this._logger.logError(error)
      );
    this.dataSub = this._dataShareService.createdPostSource$
      .subscribe(post => {
        this.posts.result.unshift(post);
        console.log(this.posts.result);
      });
  }

  createResponse(post): void {
    this._dataShareService.passData(post);
    console.log("postlist:" + post);
  }

  ngOnDestroy(): void {
    this.dataSub.unsubscribe();
  }
}

链接在html中

 <a [routerLink]="['/post',post.id]" (click)="createResponse(post)">{{post.title}}</a>

发表-detail.component.ts

@Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.component.html',
  styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {

  private _postDetailPath: string;
  private dataSub: Subscription;
  private _post: IPost;

  constructor(private _router: Router,
              private _route: ActivatedRoute,
              private _config: ConfigService,
              private _dataShareService: DataShareService,
              private _logger: ErrorLogService) {

  }

  ngOnInit() {
    this.dataSub = this._dataShareService.dataSource$.subscribe(
      post => {
        this._post = post;
        console.log('post : ' + this._post);
      }, error => {
        console.log('errr0');
        this._logger.logError(error);
      },() => {console.log('post : error' )});

  }

  onBack(): void {
    this._router.navigate(['/posts'])
  }
  ngOnDestroy() {
    this.dataSub.unsubscribe();
  }

}

无法在重定向后获取详细信息的ngOnInit()中的数据。

这是如何运作的?如果我不这样做你的作品。但是如何使它与路由一起工作?

2 个答案:

答案 0 :(得分:0)

服务必须由加载2个组件的模块或加载声明组件的两个模块的模块加载,因此您将拥有该服务的单例实例,并且可以在这两个组件之间共享数据。

在您的情况下,从组件提供程序中删除该服务并将其放在app.module提供程序中。通过这种方式,您将拥有一个单例,并且可以共享数据。

答案 1 :(得分:0)

根据帖子here修复我的。你只需要替换

new Subject<any>();

new BehaviorSubject(undefined);

然后你可能不得不在某处处理undefined取决于你如何使用它。 我知道这似乎是hacky但它​​确实有效。