我是angular和firebase的新手。当我尝试从of
导入rxjs
时,也尝试使用switchMap
返回null时,出现此错误。
auth.service.ts
import { ActivatedRoute } from '@angular/router'
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
import { AppUser } from './models/app-user'
import { AngularFireAuth } from '@angular/fire/auth';
import { switchMap } from 'rxjs/operators';
import * as firebase from 'firebase';
import { UserService } from './user.service';
@Injectable({
providedIn: 'root'
})
export class AuthService {
user$: Observable<firebase.User>;
constructor(
private userService: UserService,
private afAuth: AngularFireAuth,
private route: ActivatedRoute) {
this.user$=afAuth.authState;
}
login(){
let returnUrl=this.route.snapshot.queryParamMap.get('returnUrl')||'/'
localStorage.setItem('returnUrl',returnUrl)
this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider())
}
logout(){
this.afAuth.auth.signOut()
}
get appUser$():Observable<AppUser>{
return this.user$
.pipe(switchMap(user=> {
if(user) return this.userService.get(user.uid).valueChanges();
return Observable.of(null); <==line of error
})
}
}
user.service.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import * as firebase from 'firebase';
import { AppUser } from './models/app-user';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private db:AngularFireDatabase) { }
save(user: firebase.User){
this.db.object('/users/'+user.uid).update({
name: user.displayName,
email: user.email
})
}
get(uid: string):AngularFireObject<AppUser>{
return this.db.object('/users/'+uid)
}
}
app.user.ts
export interface AppUser{
name: string,
email:string,
isAdmin: boolean
}
获取Type 'Observable<unknown>' is not assignable to type 'Observable<AppUser>'
作为错误消息。
答案 0 :(得分:1)
尝试使用typescript optional parameters
代替name: string;
更改为name?: string;
export class AppUser {
name?: string;
email?: string;
isAdmin?: boolean;
photoURL?: string;
}
希望如此。
答案 1 :(得分:1)
您似乎已经在strictNullChecks
中启用了tsconfig.json
,因此不允许您分配null
来键入AppUser
,这是正确的。
因此,您可以将返回类型定义为Observable<AppUser | null>
,其中还包括null
值。
也许还可以尝试将RxJS升级到可能的最新版本。我认为of
的键入https://github.com/ReactiveX/rxjs/issues/4723曾经存在问题,但这可能与您的问题无关。
答案 2 :(得分:0)
感谢您的回复。通过向isAdmin?: string
和app-user.ts
中添加import { of } from 'rxjs'
...
return of(null)
工作。
答案 3 :(得分:0)
我遇到了同样的问题,我所做的只是添加<?php
// YOUR SQL CONNECT GOES HERE.
// REPLACE $data with PDO/MYSQLI QUERY DATA.
$data = [ [
( Object )["axis" => "Battery Life","value" => (rand(1, 99))],
( Object )["axis" => "Brand","value" => rand(1, 99)],
( Object )["axis" => "Contract Cost","value" => rand(1, 99)],
( Object )["axis" => "Design And Quality","value" => rand(1, 99)],
( Object )["axis" => "Have Internet Connectivity","value" => rand(1, 99)],
( Object )["axis" => "Price Of Device","value" => rand(1, 99)],
( Object )["axis" => "To Be A Smartphone","value" => rand(1, 99)],
] ];
echo json_encode($data);