我不知道角度的基本原理,特别是关于测试的理论,足以知道我是否应该更喜欢router.navigate()在组件或服务中使用.
例如,假设您有一个LogInComponent管理您的登录表单和一个AuthService处理与服务器通信的人.当用户成功登录时,您希望将它们从登录屏幕重定向到应用程序的主页.最好是这样做LogInComponent还是AuthService?
我是Angular2的新手,开始编写一个所有方法所在的应用程序main.ts,然后该文件依次引用它的视图main.html.我将此应用程序重构为子组件和服务.所以,我现在有:
- app.component.ts
- app.html
- sub.component.ts
- sub.html
- data.service.ts
Run Code Online (Sandbox Code Playgroud)
sub.component作为指令包括在内app.component.app.compontent注入data.service,我可以通过点击事件调用该服务app.component.
问题
以前,我可以从组件中的函数更新视图上的进度条.现在该函数在自己的服务中,如何更新用户有关服务中长时间运行(递归)方法的进度?我假设我必须将服务的进度传递给app.component或sub.component,但这是怎么做的?
我已经和Angular2玩了几天了,到目前为止我真的很喜欢它.但我似乎无法绕过某些东西.
我有一个带有2个函数的类userService(我删除了大多数逻辑.),它改变了IsLoggedIn属性:
@Injectable()
export class UserService{
public IsLoggedIn:bool = false
login(){
this.IsLoggedIn = true;
}
logout(){
this.IsLoggedIn = false;
}
}
Run Code Online (Sandbox Code Playgroud)
我想在全局视图中显示和隐藏一些元素,具体取决于IsLoggedIn属性.做这个的最好方式是什么?
我正在尝试在我的组件之间进行某种通信,所以我在组件中使用带有BehaviorSubject和Subscription的服务,如下所示:
服务(与问题相关的代码):
import { BehaviorSubject } from 'rxjs/BehaviorSubject'
private _clientModalActionSource = new BehaviorSubject<string>('')
modalAction$ = this._clientModalActionSource.asObservable()
public updateClientModalAction(action) {
this._clientModalActionSource.next(action)
console.log('sent')
}
Run Code Online (Sandbox Code Playgroud)
组件A:
this._api.updateClientModalAction(id)
Run Code Online (Sandbox Code Playgroud)
组件B:
import { Subscription } from 'rxjs/subscription'
private _subscription: Subscription
ngOnInit() { this._subscription = this._api.modalAction$.subscribe(res => {
this.refreshModal(res)
console.log('received')
})}
Run Code Online (Sandbox Code Playgroud)
如果组件B是组件A的子组件,这是完美的工作,但如果A是根组件而B在其内部<router-outlet>(或相反),则订阅的任何内容都没有,我只能进入sent控制台.
我究竟做错了什么?
我期待一些奇怪的情况,其中"this"在组件内部为空.到目前为止,我在两种情况下看到了它:
1)当承诺被拒绝时:
if (this.valForm.valid) {
this.userService.login(value).then(result => {
if(result.success){
this.toasterService.pop("success", "Exito", "Inicio de session correcto");
this.sessionService.setUser(result.data);
this.router.navigateByUrl('home');
}
else{
this.error = result.code;
}
},function(error){
console.log("ERROR: " + error);
this.error = "ERROR__SERVER_NOT_WORKING";
console.log(this.error);
});
}
Run Code Online (Sandbox Code Playgroud)
在函数(错误)中,这是null,因此我无法分配相应的错误.
该服务以下列方式工作:
login(login : Login) : Promise<Response> {
return this.http
.post(this.serverService.getURL() + '/user/login', JSON.stringify(login), {headers: this.headers})
.toPromise()
.then(res => res.json())
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.log('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
Run Code Online (Sandbox Code Playgroud)
因此,在调用服务handleError时,此值将丢失.
2) - 使用sweetalert …
javascript typescript angular-promise angular2-services angular
如果花费太长时间,我想忽略我的API的响应.我用
this.http.get(mysqlUrl).subscribe()
Run Code Online (Sandbox Code Playgroud)
得到回应.但是如果完成时间超过5秒,我想取消订阅.我知道我可以使用unsubscribe(),但是如何将其链接到超时值?
谢谢!
当我尝试将服务注入到我的组件时,我收到此错误
我正在进行Service调用以从MongoDB获取数据.这部分似乎正在工作,它在控制台中正确记录.
这个响应非常大,可能需要大约8秒才能完全进入数据.为此,我希望能够data[]在检索到数据后更新组件.
我目前的解决方案不起作用,我想知道实时检索这个的正确和最佳实践.即使响应时间稍长.
服务调用getData
export class DataService {
dataArray: any[];
constructor(private http: Http){}
//get all data
getData(): any {
console.log('Api is calling getData...');
this.http.get('http://localhost:8080/api/data').map((res: Response) => res.json()).subscribe((res: any) => {
this.dataArray = res;
console.log('JSON: ' + this.dataArray);
return this.dataArray;
});
}
}
Run Code Online (Sandbox Code Playgroud)
这正确地导入MainComponent,没有错误.
MainComponent
export class MainComponent implements OnInit{
data: Array<any>;
//Inject service here to use for getting data
constructor(private dataService: DataService){}
ngOnInit(){
//Set View Data with Request from Server
this.data = this.dataService.getData();
console.log("Data: " + this.data);
} …Run Code Online (Sandbox Code Playgroud) 我有问题,我想从服务器来到我的属性组件后接收数据.
我在服务中做了这样的事情:
private events: Event[] = [];
eventChanged = new Subject<any>(); // Edit: added an observable
constructor(private http: HttpClient) {
this.http.get<Event[]>(this.baseUrl)
.subscribe(events => this.events = events);
this.eventChanged.next(this.events.slice()); //Edit: added an information to subscribers that events list changed
}
getEvents(): Observable<Event[]> {
return this.eventChanged.asObservable();
} // Edit: now I use this method to enables subscribers to observable
/* I don't use that method after Edit
showAllEvents(): Event[] {
return [...this.events];
}
*/
Run Code Online (Sandbox Code Playgroud)
然后我使用方法showAllEvents()进入我的组件,如下所示:
private events: Event[] = [];
private …Run Code Online (Sandbox Code Playgroud) NullInjectorError:类形成没有提供者!
// Component
import { Formation } from '../../Models/Formation';
@Component({
selector: 'app-formation',
templateUrl: './formation.component.html',
styleUrls: ['./formation.component.scss'],
})
export class FormationComponent {
constructor(private formation: Formation) { }
}
// Model Class
export class Formation {
}
Run Code Online (Sandbox Code Playgroud)
有什么问题吗?