0

我正在尝试制作一个类似于 pastebin.com 的应用程序,我可以在其中使用语法高亮显示。现在我正在尝试制作共享文件方法。我从 .NET Core API 获取所有数据,而响应正是我所需要的。

问题是当我打开共享链接时,组件在承诺解决之前被初始化。

假设我想打开以下链接: http://localhost:4200/shared/1

当我打开链接时,文件 = 1的数据被提取并放置在模型中。然后我希望加载组件并显示 html。

我不明白解析器是如何工作的,我该怎么办?谢谢。

用户服务.ts

@Injectable({
    providedIn: 'root'
})
export class UserService implements Resolve<any> {

resolve(route: ActivatedRouteSnapshot){
        console.log('Logging collected route parameter', route.params['file']);
        this.http.get(this.BaseURL + '/Share?IdentityString=' + route.params['file'])
        .subscribe(res =>{
        this.sharedFormData = res as ShareModel;

        console.log(this.sharedFormData);
    });
      }
}

应用程序路由.module.ts

export const routes: Routes = [
  { 
    path: 'shared/:file',
    component: FileShareComponent,
    resolve: {
      shared: UserService
    }
  }
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

文件共享.component.html

export class FileShareComponent implements OnInit {

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private service: UserService,
    private http: HttpClient
  ) {}

  ngOnInit() {
    console.log('Component initialized');
  }
}

文件共享.component.html

<pre class="text-white"style="color: white;">Name: {{service.sharedFormData?.Name}}</pre>
<pre style="color: white;">Description: {{service.sharedFormData?.Description}}</pre>
<pre style="color: white;">Syntax: {{service.sharedFormData?.Syntax}}</pre>
<pre style="color: white;">LastModified: {{service.sharedFormData?.LastModified | date: "HH:mm dd/MM/yyyy"}}</pre>
<pre style="color: white;">ExpirationDate: {{service.sharedFormData?.ExpirationDate | date: "HH:mm dd/MM/yyyy"}}</pre>
<pre><code class="hljs">{{service.sharedFormData?.Content}}</code></pre>

这是 URL 的外观: http://localhost:4200/shared/MThBU1AgLk5FVCBDb3Jl

控制台日志

4

1 回答 1

0

您必须在方法中返回 Observable/Promise,resolve()以便在组件初始化之前完成 HTTP 请求。另请注意,您不应订阅该resolve()方法中的 HTTP 调用。只需按原样返回即可。如果要记录/存储数据,请使用tap()rxjs 运算符。

修改您的代码如下:

解析器:

@Injectable({
    providedIn: 'root'
})
export class UserService implements Resolve<any> {

  resolve(route: ActivatedRouteSnapshot){
    console.log('Logging collected route parameter', route.params['file']);
    return this.http.
      get(this.BaseURL + '/Share?IdentityString=' + route.params['file'])
      .pipe(tap(res => console.log('Response from HTTP req: ', res)));
  }
}

零件:

export class FileShareComponent implements OnInit {

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private service: UserService,
    private http: HttpClient
  ) {}

  ngOnInit() {
    console.log('Component initialized');
    this.route.data.subscribe((data: { shared: any }) => {
      let formData = data.shared as ShareModel;
      // perform your logic now
    });
  }
}

可以在此处找到有关解析器的更多信息。

于 2020-03-02T14:13:33.240 回答