无法在Angular 2中使用解析 [英] Not able to Use Resolve in Angular 2

查看:59
本文介绍了无法在Angular 2中使用解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用angular4渲染视图之前先加载对象,所以我选择使用angular4的resolve,但是我无法获取数据,不知道我在做什么错.

I want to load object before the view is rendered in angular4, so i choose to use resolve of angular4 but i am not able to get data, dont know what am i doing wrong.

这是我的模块

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ActivatedRoute, Routes, RouterModule } from '@angular/router';
import { ResolverService } from './resolver.service';

export const routes: Routes = [
  { path: '', component: AppComponent, resolve: { transaction: ResolverService } }
];

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    RouterModule.forRoot(routes),
    BrowserModule,
    FormsModule
  ],
  providers: [ResolverService],
  bootstrap: [AppComponent]
})
export class AppModule { }

我的解析器服务

import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ResolverService implements Resolve<any> {
  constructor(private router: Router) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
    return new Observable(observer => {
      setTimeout(function () {
        observer.next(150)
      }, 1000);
    });
  }  
}

这是我的组件

import { Component, AfterViewInit, APP_INITIALIZER, InjectionToken, Inject } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot, ActivatedRoute } from '@angular/router';
import { student } from './sa-model.service';
import { Observable } from 'rxjs/Observable';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  constructor(private route: ActivatedRoute) {
  }

  ngAfterViewInit() {
    this.route.data.subscribe(success => {
      debugger;
      console.log(success);
    })
  }

}

但是在组件中,我希望获得在解析器服务中传递的值150,但是我没有任何值

but in the component i was expecting to get the value 150 which i am passing in the resolver service, but i am not getting any values

任何人都可以指导我做错什么事

can any one guide me on what exactly am in doing wrong

推荐答案

这是因为您打开了可观察对象,但在返回它之前从未完成它,因此什么也不会返回.添加此内容:

It's because you opened the observable but never completed it before returning it, so nothing gets returned. Add this:

setTimeout(function () {
  observer.next(150);
  observer.complete(); // Need to call complete once done.
}, 1000);

这篇关于无法在Angular 2中使用解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆