TS2345:“字符串”类型的参数 | null' 不可分配给类型为 'string | 的参数 | UrlTree'

问题描述

这个问题的标题是 Angular CLI 编译器抛出的信息。

我的 app.component.ts 中有这个构造函数

    export class AppComponent {
      constructor(private userService: UserService,private auth: AuthService,router: Router) {
       auth.user$.subscribe(user => {
        if (user) {
         userService.save(user);

         let returnUrl = localStorage.getItem('returnUrl');
         router.navigateByUrl(returnUrl);
      }
    });
  }
}

在上面附加的代码部分中,我有下划线的“returnURL”,如果我将光标放在上面,它会说:

“'string | null' 类型的参数不能分配给 'string | UrlTree' 类型的参数。 类型 'null' 不能分配给类型 'string | UrlTree'。”

我有一个与 Firebase 相关的 user.service.ts:

    import { Injectable } from '@angular/core';
    import { AngularFireDatabase } from 'angularfire2/database';
    import * as firebase from 'firebase';

    @Injectable()
    export class UserService {

        constructor(private db: AngularFireDatabase) { }
  
          save(user: firebase.User) {
          this.db.object('/users/' + user.uid).update({
            name: user.displayName,email: user.email
         });
       }
     }

有没有人知道这里的编译器问题是什么?我还附上了控制台消息。

Console message

解决方法

错误为您提供了所需的所有信息。

localStorage.getItem 返回字符串或 null,而 router.navigateByUrl 需要 stringUrlTree 的参数。您必须在调用 router.navigateByUrl 之前检查 localStorage.getItem 的返回值以确保它不为 null,因为您不能使用 null 调用它。

let returnUrl = localStorage.getItem('returnUrl');
if (returnUrl) { // i.e,not null and not empty string 
    // now returnUrl cannot be null,so it must be a string,which is valid to use in this call
    router.navigateByUrl(returnUrl);
}
,

您可以使用感叹号告诉编译器该值不能为空,如下所示:


test <- tibble(project = c("big","low","medium","superbig"),capacity = c(10,5,16,3),date = c("Aug 2021","Aug 2021","Sep 2021","Sep 2021"),date_num = as.Date("2021-08-01","2021-08-01","2021-09-01","2021-09-01")) %>%
  dplyr::mutate(date = reorder(date,date_num))

plot_ly(test,x = ~date,y = ~capacity,type = 'bar',name = ~project,color = ~project,colors = ~all_colors[seq_along(unique(project))]) %>%
  layout(legend = list(orientation = 'h',x = .5,xanchor = "center",y = -.3),barmode = "stack")
,

你有线路

let returnUrl = localStorage.getItem('returnUrl');

getItem() 函数返回一个 null | string。如果该项目不在存储中,则函数返回 null。

router.navigateByUrl(returnUrl); 期望 returnUrlstring | UrlTree 类型,但 returnUrl 从其初始化推断为 null | string 因此错误

有多种方法可以解决这个问题,一个简单的方法是将返回值类型转换为字符串

let returnUrl = localStorage.getItem('returnUrl') as string;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...