我正在使用angular2开发一个应用程序.我有一个场景,我需要在路由时使用复杂数据(对象数组)从一个组件传递到另一个组件(它们不是父子,它们是两个独立的组件)(使用router.navigate()).我用Google搜索了这一点,大部分结果都描述了父子组件的场景.我已经完成了结果并找到了传递数据的方法.
1)创建共享服务2)作为路由参数传递
第二种方法对我有效(尽管如此,当我有如上所述的复杂数据时,我不喜欢这种方法).我无法使用共享服务共享数据.所以我的问题是,使用服务的组件之间传递数据只在组件处于父子关系时才有效吗?另外,请告诉我是否还有其他优先方法可以在一个组件和另一个组件之间传递数据?
更新:我在我的场景中添加了一些代码.请让我知道为什么通过共享服务传递数据不起作用的错误.
我有2个组件:1)SearchComponent 2)TransferComponent我在SearchComponent中设置数据,并希望通过utilityService访问TransferComponent中的数据.
公用事业服务
import {Injectable} from "@angular/core";
@Injectable()
export class UtilityService{
constructor(){
}
public bioReagentObject = [];
routeBioReagentObj(bioReagentObj){
console.log("From UtilityService...", bioReagentObj);
for (let each of bioReagentObj)
this.bioReagentObject.push(each)
// console.log("From UtilityService",this.bioReagentObject);
}
returnObject(){
console.log("From UtilityService",this.bioReagentObject);
return this.bioReagentObject
}
}
Run Code Online (Sandbox Code Playgroud)
searchcomponent.ts
import {UtilityService} from "../services/utilityservice.component";
import {Component, OnInit, OnDestroy, Input} from '@angular/core';
@Component({
selector: 'bioshoppe-search-details',
providers: [UtilityService],
templateUrl: 'app/search/searchdetails.component.html',
styleUrls: ['../../css/style.css']
})
export class SearchDetailsComponent implements OnInit, OnDestroy {
constructor(private route: ActivatedRoute,
private utilityService: UtilityService,
private router: Router) …Run Code Online (Sandbox Code Playgroud) 我正在开发一个 Angular(v4) 应用程序。像任何其他网络应用程序一样,这个应用程序也有HTTP请求,对于这些请求中的每一个,我都有一个订阅来获取数据并将它们显示在 UI 上。我一直在阅读有关async管道的使用以及为什么它比subscribe. 从我读过的内容来看,它肯定比普通subscribe方法有好处,我确信我应该在我的应用程序中使用它,但我不确定如何使用这个aync管道而不是subscribe. 让我发布我的应用程序的结构:
我有一个Http向后端发出请求的服务层,例如:
some-service.component.ts
@Injectable()
export class SomeService {
constructor(private http: HttpClient) {
}
getSomething() {
return this.http.get(`${this.baseUrl}/${'test'}`);
}
}
Run Code Online (Sandbox Code Playgroud)
上述服务为我的组件提供了一个 Observable,我通常在其中订阅它,如下所示:
一些组件.ts
@Component({
selector: 'some-app',
templateUrl: './some.component.html',
styleUrls: []
})
export class SomeComponent {
constructor(private someService: SomeService) {
}
getSomething() {
this.someService
.getSomething()
.subscribe(
// the first argument is a function which runs on success
(data) => {
// DO …Run Code Online (Sandbox Code Playgroud) 我知道可以使用session_transaction()方法创建会话对象。但是,有没有办法访问当前会话对象,例如当“ /”路由被命中时创建的会话对象?我确实from flask import session访问了该会话,但是它是空的。让我知道是否可能。谢谢。