路由更改时角度重置TransferState数据

时间:2019-06-04 11:35:47

标签: angular angular-universal angular-transfer-state

我正在将Angular与服务器端渲染和TransferState一起使用,以将HTTP数据从服务器传输到浏览器。这是我的代码:

getProducts() {
    let products = this.tstate.get(PRODUCT_KEY, null as any);
    if (products) {
        return of(products);
    }

    return this.http.post<any>(config.baseUrl+ 'product', {}).pipe(map(
        data => {
            this.tstate.set(PRODUCT_KEY, data as any);
            return data;
        }
    ))
}

在第一次加载中,我从http请求中获取数据。然后状态正在初始化。此后,当路由更改时,仍处于传输状态的数据仍然保留,因此我无法发送获取数据的请求。知道如何在更改路线时重置传输状态吗?

1 个答案:

答案 0 :(得分:1)

您可以在导航后收听路由器事件并取消设置缓存数据

USE [Inventory]
GO
/****** Object:  StoredProcedure [dbo].[GetInventoryByAssetDescription]    Script Date: 6/4/2019 8:30:15 AM ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[GetInventoryByAssetDescription]
      (
            @SearchString varchar(30),
            @DispositionText varchar(200),
            @Title1Item bit
      )  
AS
begin
    SET NOCOUNT ON
    declare @sql nvarchar (2000)

    select @SearchString=UPPER(@SearchString)
    set @sql = '   select in_eq_ID,
        in_eq_TagNumber as TagNumber,
        Title1Item,
        in_eq_AssetDescription as Description,
        in_eq_ExtendedDescription as ExtendedDescription,
        in_eq_SerialNumber as SerialNumber,
        in_eq_ValuationAmount as TotalValue,
        in_eq_CustodianName as Name,
        in_eq_ComplexBuilding as ShortLocation,
        in_eq_SubLocationCode as ShortRoomNumber,
        in_ca_Categories.in_ca_CategoryName as CategoryName,
        in_eq_DispositionDate as DispositionDate,
        DATEADD (dd, 0, DATEDIFF (dd, 0, in_eq_Equipment.in_eq_AcquisitionDate)) as AcquisitionDate
        from in_eq_Equipment
            LEFT JOIN in_ca_Categories ON in_eq_Equipment.in_eq_CategoryID_fk = in_ca_Categories.in_ca_CategoryID
            where @Title1Item = Title1Item
                AND upper (in_eq_AssetDescription) LIKE upper ('''+ @SearchString + ''')'

        set  @sql=@sql+'   ' + ISNULL(@DispositionText,' ')  + '  order by in_eq_AssetDescription'
        execute (@sql)
        return
end

或者如果您是客户端,则可以停止设置传输数据

constructor(private router: Router,
//...)
{
  this.router.events.subscribe(evt => {
  if (evt instanceof NavigationEnd)
  {
    this.tstate.remove(PRODUCT_KEY);
  }

}