问题
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:
window.location.href = 'http://...';
window.location = 'http://...';
来源:https://stackoverflow.com/questions/48004605/window-object-in-angular-5-service