Window object in angular 5 service

会有一股神秘感。 提交于 2019-12-24 08:05:06

问题


I have project in Angular, user's panel in specific. All page is in php, just panel in angular. How to use window object in service?

I want use window.location exactly for the same action as href="/" in HTML, which return me to outside the angular project(panel) to main site. Why? When I was trying get user and it returns status for example 401, 404 user can not get access to panel, and it must navigate to main site.

I tried several options with route navigate or navigateByURl, but address was always set to baseHref in Angular, so I could not go outside. I tried pass {provide: Window, useValue: window } in providers, inject window to the constructor in service and this is working on my localhost, but when I run ng build in cli it sends mi a error:

ERROR in Error: Can't resolve all parameters for UserService in ../my-app/src/app/user.service.ts: (?, [object Object], [object Object], [object Object], [object Object]).

Anyone please?

In AppModule:

providers: [UserService, DatePipe, {provide: Window, useValue: window }],

in UserSerice:

constructor(private window: Window, private location: Location, private HttpClient: HttpClient, private route: ActivatedRoute, private router: Router){};

and function in UserService to navigate on status:

if(data == 403) {
  this.setError('You must log in', 'danger');

  this.window.location.assign("/");
  ...
}

回答1:


ERROR in Error: Can't resolve all parameters for UserService in ../my-
app/src/app/user.service.ts: (?, [object Object], [object Object], 
[object Object], [object Object]).

This error occurs because angular is trying to inject Window and Location into your service and can't find corresponding classes with @Injectable decorator. The @Injectable decorator indicates that the Angular DI system is used to create one or more instances of the class. Also window is a globally accessible object.

So instead of this.window.location.assign("/"); you could use window.location.assign("/");

Or any of this:

  1. window.location.href = 'http://...';
  2. window.location = 'http://...';


来源:https://stackoverflow.com/questions/48004605/window-object-in-angular-5-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!