Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 7服务不作为单体_Angular_Typescript_Service_Singleton - Fatal编程技术网

Angular 7服务不作为单体

Angular 7服务不作为单体,angular,typescript,service,singleton,Angular,Typescript,Service,Singleton,我使用ng generate创建了一个服务。我初始化一个数组并更改一个标志,但当我路由到另一个页面时,该数组为空,标志为false 我的服务始于 @可注入({ providedIn:'根' }) 我知道这将创建一个应用程序范围的单例服务,但我以前只在单页应用程序上使用过服务。与多页应用程序/路由不同吗 编辑:我已经尝试将字段设置为静态,但也不起作用 编辑2:这或多或少是我的问题:在主页上初始化并显示(true)。导航到admin(在主页上初始化之后)并显示(false) 我相信(从上面的stac

我使用
ng generate
创建了一个服务。我初始化一个数组并更改一个标志,但当我路由到另一个页面时,该数组为空,标志为false

我的服务始于

@可注入({
providedIn:'根'
})

我知道这将创建一个应用程序范围的单例服务,但我以前只在单页应用程序上使用过服务。与多页应用程序/路由不同吗

编辑:我已经尝试将字段设置为静态,但也不起作用

编辑2:这或多或少是我的问题:在主页上初始化并显示(true)。导航到admin(在主页上初始化之后)并显示(false)

我相信(从上面的stackblitz示例中)您的问题在于您使用的是
href
而不是
routerLink=“/home”
指令。由于
href
将使用新uri完全重新加载您的页面,因此重新初始化服务似乎是合法的,因为整个应用程序都是从头启动的

因此,底线是,如果您只是将
href
替换为
路由器链接
,那么通过应用程序提供的服务将只有一个实例


如果是完全不同的页面(而不是SPA的不同路径),您的价值将不会保存,因为应用程序已被销毁。啊,是的,它似乎是一个不同的页面。我是否使用磅符号为SPA进行路由?你应该使用@angular/router module以angular实现路由。我是,这是我在我的应用程序路由模块中拥有的:
const routes:routes=[{path:'',重定向到:'home',pathMatch:'full'},{path:'home',component:HomeComponent},{path:'submit component},{path:'admin',component:AdminComponent},{path:'calendar',component:CalendarComponent},{path:'edit',component:EditComponent}]在stackblitz中发布一个完整的最小示例,再现问题。这解决了问题,至少在stackblitz中是这样。我明天去办公室试试。上帝保佑。